概念
单向循环链表是单链表的一个变形,链表中最后一个节点的指针域不再指向None,而是指向链表的头节点。
单向循环链表实现
class SingleCycleLinkList:
def __init__(self, node=None):
self.__head = None
self.__count = 0
if node is not None:
self.__head = node
# 尾节点指针域指向头节点
node.next = node
self.__count += 1
def is_empty(self):
return self.__head == None
def length(self):
return self.__count
def travel(self):
if self.is_empty():
return
cur = self.__head
while cur.next != self.__head:
yield cur.item
cur = cur.next
# 退出循环时,cur指向尾节点
return cur.item
def add(self, item):
node = SingleNode(item)
if self.is_empty():
self.__head = node
node.next = node
else:
node.next = self.__head
self.__head = node
cur = self.__head
while cur.next != self.__head.next:
cur = cur.next
cur.next = node
self.__count += 1
def append(self, item):
if is_empty():
self.add(item)
else:
node = SingleNode(item)
cur = self.__head
while cur.next != self.__head:
cur = cur.next
node.next = self.__head
cur.next = node
def insert(self, item, pos):
if pos <= 0:
self.add(item)
elif pos > self.__count - 1:
self.append(item)
else:
pre = self.__head
count = 0
while count < pos - 1:
count += 1
pre = pre.next
node = SingleNode(item)
node.next = pre.next
pre.next = node
def remove(self, item):
if self.is_empty():
return
cur = self.__head
pre = None
while cur.next != self.__head:
if cur.item == item:
# 如果要删除的是头部节点
if cur == self.__head:
# 查找最后一个节点 rear
rear = self.__head
while rear.next != self.__head:
rear = rear.next
self.__head = cur.next
rear.next = self.__head
# 如果不是头节点,直接删除即可
else:
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
# 退出循环时,cur指向尾节点
if cur.item == item:
# 如果链表中只有一个头节点
if cur == self.__head:
self.__head = None
else:
pre.next = cur.next
def search(self, item):
if self.is_empty():
return False
cur = self.__head
while cur.next != self.__head:
if cur.item == item:
return True
else:
cur = cur.next
# 退出循环时,此时cur指向的是最后一个元素
if cur.item == item:
return True
return False
注意单向循环链表的遍历过程比一般的链表复杂。