class Node:
def __init__(self, elem, next=None):
self.elem = elem
self.next = next
class SingleLinkList:
"""单向循环链表"""
def __init__(self, node=None):
self.__head = node
if node:
node.next = node
def is_empty(self):
"""链表是否为空"""
return self.__head is None
def length(self):
"""链表长度"""
count = 1
cur = self.__head
if cur:
while cur.next is not self.__head:
count += 1
cur = cur.next
return count
else:
return 0
def travel(self):
"""遍历整个链表"""
if self.is_empty():
return
cur = self.__head
print(cur.elem, end=' ')
while cur.next is not self.__head:
cur = cur.next
print(f'{cur.elem} ', end='')
print('')
def add(self, elem):
"""链表头部添加信息"""
node = Node(elem)
if self.is_empty():
self.__head = node
node.next = node
else:
cur = self.__head
while cur.next is not self.__head:
cur = cur.next
cur.next = node
node.next = self.__head
self.__head = node
def append(self, elem):
"""链表尾部添加元素"""
if self.__head is None:
self.add(elem)
else:
cur = self.__head
while cur.next is not self.__head:
cur = cur.next
cur.next = Node(elem, next=self.__head)
def insert(self, pos, elem):
"""指定位置添加元素"""
if pos <= 0:
self.add(elem)
elif 0 < pos < self.length():
cur = self.__head.next
pre = self.__head
while pos > 1:
cur = cur.next
pre = pre.next
pos -= 1
node = Node(elem, cur)
pre.next = node
else:
self.append(elem)
def remove(self, elem):
"""删除节点"""
if self.is_empty():
print('列表为空')
return
pre = None
cur = self.__head
while cur.next is not self.__head:
if cur.elem == elem:
# 如果删除的是第一个节点
if not pre:
# 如果列表只有一个节点
if cur.next == self.__head:
self.__head = None
else:
self.__head = cur.next
# 删除的是最后一个节点
elif cur.next == self.__head:
pre.next = self.__head
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
else:
print('没有这个值')
def search(self, elem):
"""查找节点是否存在"""
if self.is_empty():
print("列表为空")
return
cur = self.__head
while cur.next is not self.__head:
if cur.elem == elem:
return True
else:
cur = cur.next
if cur.elem == elem:
return True
else:
return False
if __name__ == '__main__':
pass
# 测试过程省略
python数据结构:03单向循环链表
最新推荐文章于 2024-09-07 09:36:10 发布