单向循环链表
class Node:
def __init__(self, item):
self.item = item
self.next = None
self.prev = None
class CycleLink:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def length(self):
if self.head == None:
return 0
cur = self.head
count = 1
while cur.next != self.head:
count += 1
cur = cur.next
return count
def travel(self):
if self.head == None:
return 0
cur = self.head
while cur.next != self.head:
print(cur.item)
cur = cur.next
def add(self, item):
node = Node(item)
if self.is_empty():
self.head = node
node.next = self.head
else:
node.next=self.head
cur=self.head
while cur.next!=self.head:
cur=cur.next
cur.next=node
self.head=node
link = CycleLink()
print(link.length())
link.add(123)
print(link.length())
print('----------')
link.add(125)
link.add(126)
link.travel()
单向循环链表特点是最后一个节点并不是指向None,而是指向的是head指针。
单向循环链表的判断是否为空与单链表一样。求长度和遍历与单链表的条件判断不一样,判断的是是否为head指针。