1. 单向循环链表
单向循环链表(Singly circular linked list)next

接下来我们使用Python 3来构建单向循环链表数据结构,首先需要定义一个节点类:
class Node:
'''单向循环链表的节点'''
def __init__(self, value):
self.value = value # 节点的信息域
self.next = None # 节点的指针域
def __repr__(self):
return 'Node({!r})'.format(self.value)
然后定义单向循环链表类:
class SinglyCircularLinkedList:
def __init__(self, node=None):
'''创建一个单向循环链表对象时,如果不传入头节点,则创建空链表'''
self.__head = node
if node:
node.next = node # 如果创建非空链表,它的 next 要指向头节点,即指向它自身
2.1 判断是否空链表
__head
def is_empty(self):
'''判断是否为空链表'''
return self.__head is None
2.2 求链表的长度
curcur = self.__headcountcurcur.next == self.__head
count
def length(self):
'''求链表的长度'''
if self.is_empty():
return 0 # 空链表直接返回0
cur = self.__head # 游标,用来表示当前节点
count = 0 # 用来统计已遍历的节点数目
while True:
count += 1
if cur.next == self.__head: # 遍历到尾节点时,cur.next == self.__head,需要退出循环
break
cur = cur.next # 向后移动游标
return count
2.3 遍历链表
逻辑跟求长度一样,注意,这里使用生成器语法,将每个节点的值产出供客户代码使用
def travel(self):
'''遍历整个链表'''
if self.is_empty():
return
cur = self.__head # 游标,用来表示当前节点
while True