节点抽象类型定义
class SingleNode:
def __init__(self, item):
self.item = item
self.next = None
链表抽象类型
class SingleList:
def __init__(self, head_node=None):
self.__head = head_node
def is_empty(self):
if self.__head is None:
return True
else:
return False
def length(self):
cursor = self.__head
count = 0
while cursor is not None:
count += 1
cursor = cursor.next
return count
def travel(self):
cursor = self.__head
while cursor is not None:
print(cursor.item, end=' ')
cursor = cursor.next
print()
def add(self, item):
new_node = SingleNode(item)
new_node.next = self.__head
self.__head = new_node
def append(self, item):
new_node = SingleNode(item)
cursor = self.__head
if self.is_empty():
self.__head = new_node
else:
while cursor.next:
cursor = cursor.next
cursor.next = new_node
def insert(self, pos, item):
new_node = SingleNode(item)
cursor = self.__head
if pos < 0 or not isinstance(pos, int):
print('节点位置必须是正整数!')
elif self.length() + 1 < pos:
print('插入位置已超过链表最大长度!')
else:
if pos == 1:
new_node.next = self.__head
self.__head = new_node
else:
for _ in range(1, pos - 1):
cursor = cursor.next
new_node.next = cursor.next
cursor.next = new_node
def remove(self, item, whole=False):
cursor = self.__head
if whole:
while cursor:
if cursor.item == item:
self.__head = cursor.next
cursor = self.__head
elif cursor.next and cursor.next.item == item:
cursor.next = cursor.next.next
else:
cursor = cursor.next
else:
while cursor:
if cursor.item == item:
self.__head = cursor.next
break
elif cursor.next and cursor.next.item == item:
cursor.next = cursor.next.next
break
cursor = cursor.next
def search(self, item):
cursor = self.__head
while cursor:
if cursor.item == item:
return True
else:
cursor = cursor.next
return False
def count(self, item):
count = 0
cursor = self.__head
while cursor:
if cursor.item == item:
count += 1
cursor = cursor.next
return count