python 数据结构之 单向链表 的定义以及类函数的定义:
class Node(object): # 定义节点类: 单个节点
"""
An object for storing a single node in a linked list
Attributes:
data: Data stored in node
next: Reference to next node in linked list
"""
def __init__(self, data_in, next_in = None):
self.data = data_in
self.next = next_in
def __repr__(self):
return str(self.data)
class SinglyLinkedList(object):
"""
Linear data structure that stores values in nodes. The list maintains a reference to
the first node, also called head. Each node points to the next node in the list
Attributes:
head_node: The head node of the list
"""
def __init__(self):
self.head_node = None
# Maintaining a count attribute allows for len() to be implemented in
# constant time
self.__count = 0
def is_empty(self):
"""
Determines if the linked list is empty
Takes O(1) time
"""
return self.head_node is None
def __len__(self):
"""
Returns the length of the linked list
Takesn O(1) time
"""
return self.__count
def add(self, data):
"""
Adds new Node containing data to head_node of the list
Also called prepend
Takes O(1) time
"""
new_node = Node(data, next_in =self.head_node)
self.head_node = new_node
self.__count += 1
def search(self, key):
"""
Search for the first node containing data that matches the key
Returns the node or `None` if not found
Takes O(n) time
"""
curr_node = self.head_node
while curr_node:
if curr_node.data == key:
return curr_node
else:
curr_node = curr_node.next
return None
def insert(self, data, index):
"""
Inserts a new Node containing data at index position
Insertion takes O(1) time but finding node at insertion point takes
O(n) time.
Takes overall O(n) time.
"""
if index >= self.__count:
raise IndexError('index out of range')
if index == 0:
self.add(data)
return
if index > 0:
new = Node(data)
curr_node = self.head_node
"""
position = index
while position > 1:
curr_node = curr_node.next
position -= 1
"""
while index-1:
curr_node = curr_node.next
index -= 1
prev_node = curr_node
next_node = curr_node.next
prev_node.next = new
new.next = next_node
self.__count += 1
def node_at_index(self, index):
"""
Returns the Node at specified index
Takes O(n) time
"""
if index >= self.__count:
raise IndexError('index out of range')
if index == 0:
return self.head_node
current = self.head_node
position = 0
while position < index:
current = current.next
position += 1
return current
def remove(self, key):
"""
Removes Node containing data that matches the key
Returns the node or `None` if key doesn't exist
Takes O(n) time
"""
current = self.head_node
previous = None
found = False
while current and not found:
if current.data == key and current is self.head_node:
found = True
self.head_node = current.next
self.__count -= 1
return current
elif current.data == key:
found = True
previous.next_node = current.next
self.__count -= 1
return current
else:
previous = current
current = current.next
return None
def remove_at_index(self, index):
"""
Removes Node at specified index
Takes O(n) time
"""
if index >= self.__count:
raise IndexError('index out of range')
current = self.head_node
if index == 0:
self.head_node = current.next
self.__count -= 1
return current
position = index
while position > 1:
current = current.next
position -= 1
prev_node = current
current = current.next
next_node = current.next
prev_node.next = next_node
self.__count -= 1
return current
def __iter__(self):
curr_node = self.head_node
while curr_node:
yield curr_node
curr_node = curr_node.next
def __repr__(self):
"""
Return a string representation of the list.
Takes O(n) time.
"""
nodes = []
curr_node = self.head_node
while curr_node:
if curr_node is self.head_node:
nodes.append("[Head: %s]" % curr_node.data)
elif curr_node.next is None:
nodes.append("[Tail: %s]" % curr_node.data)
else:
nodes.append("[%s]" % curr_node.data)
curr_node = curr_node.next
return ' -> '.join(nodes)
if __name__ == '__main__':
N1 = Node(12)
N2 = Node(22)
# print(N1)
ll1 = SinglyLinkedList()
ll1.add(13)
ll1.add(23)
ll1.add(33)
ll1.add(43)
ll1.add(N1)
ll1.add(N2)
print(len(ll1))
ll1.insert(100, 1)
print(ll1)
for i in ll1: # def __iter__(self): 赋予了 类实例的可迭代特性
print(i)
运行结果:
6
[Head: 22] -> [100] -> [12] -> [43] -> [33] -> [23] -> [Tail: 13]
22
100
12
43
33
23
13