#单向循环链表增删查询功能实现
节点的创建
class Node(object):
"""单向循环列表节点"""
def __init__(self, item):
# 用于存放元素
self.item = item
# 用于存放下一节点标识
self.next = None
单项循环链表功能实现
class Singly_Linked_Circular_List(object):
def __init__(self, node=None):
# 空链表head = None
# 非空链表node.next = node
self.__head = node
if node:
node.next = node
def is_empty(self):
"""空链表"""
return self.__head == None
def length(self):
"""获取列表长度"""
# 判断是否空链表
if self.is_empty():
return 0
# 判断最后一个节点的位置
# cur指向首节点
cur = self.__head
count = 1
while cur.next != self.__head:
cur = cur.next
count += 1
return count
def travel(self):
"""遍历"""
if self.is_empty():
return None
cur = self.__head
while cur.next != self.__head:
print(cur.item, end=' ')
cur = cur.next
# 退出循环的时候cur指向尾结点,但是尾结点没有打印
print(cur.item)
def add(self, item):
# 先创建一个保存添加元素的节点
node = Node(item)
# 特殊情况,空链表
# 因此,加上条件判断语句
if self.is_empty():
self.__head = node
node.next = self.__head
else:
# 将游标移动到表尾
cur = self.__head
while cur.next != self.__head:
cur = cur.next
# 尾结点指向新节点
cur.next = node
# 新节点指向原头节点
node.next = self.__head
# 头节点指向新节点
self.__head = node
def append(self, item):
"""尾部添加"""
node = Node(item)
if self.is_empty():
self.__head = node
node.next = self.__head
else:
cur = self.__head
while cur.next != self.__head:
cur = cur.next
# 原尾结点指向node
cur.next = node
# node指向head
node.next = self.__head
def insert(self, pos, item):
"""指定位置插入"""
# 特殊情况pos为负或0 执行表头插入
if pos <= 0:
self.add(item)
# 特殊情况2,pos大于列表长度,执行表尾插入
elif pos > (self.length() - 1):
self.append(item)
else:
node = Node(item)
cur = self.__head
count = 0
while count < (pos - 1):
count += 1
cur = cur.next
node.next = cur.next
cur.next = node
def remove(self, item):
"""删除指定元素"""
# 空链表
if self.is_empty():
return
cur = self.__head
pre = None
# 头节点的元素就是要删除的元素
if cur.item == item:
# 链表中的节点不止一个
if cur.next != self.__head:
while cur.next != self.__head:
cur = cur.next
# 循环结束 cur指向尾结点
cur.next = self.__head.next
self.__head = cur.next
else:
self.__head = None
# 第一个节点不是要删除的
else:
while cur.next != self.__head:
if cur.item == item:
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
# 如果最后一个节点是要删除的元素
if cur.item == item:
pre.next = cur.next
def search(self, item):
"""判断列表元素"""
cur = self.__head
if self.is_empty():
return False
while cur.next != self.__head:
if cur.item == item:
return True
else:
# 让游标继续查找
cur = cur.next
# 如果最后一个元素是要查询的元素
if cur.item == item:
return True
return False
node = Node(111)
s = Singly_Linked_Circular_List(node)
print(s.length())
s.travel()
s.add(222)
s.add(333)
s.append(444)
s.append(555)
s.travel()
s.remove(333)
s.remove(555)
s.travel()
print(s.search(555))