单向循环链表
class Node(object):
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleCycleLinkList(object):
def __init__(self, node=None):
self.__head = node
if node: # 如果是None就别next了
node.next = node # 尾节点指向头结点
def is_empty(self):
return self.__head is None
def length(self):
if self.is_empty(): # 不做判空的话,空链表会返回count=1
return 0
cur = self.__head
count = 1
while cur.next != self.__head:
count += 1
cur = cur.next
return count
def travel(self):
if self.is_empty():
return '空链表'
cur = self.__head
while cur.next != self.__head:
print(cur.elem, end=' ')
cur = cur.next
print(cur.elem) # 循环丢掉了最后一个节点
def add(self, item):
if self.is_empty():
self.__head = node
node.next = node
else:
node = Node(item)
node.next = self.__head
cur = self.__head
while cur.next != self.__head:
cur = cur.next
cur.next = node
self.__head = node
def append(self, item):
node = Node(item)
if self.is_empty():
self.__head = node
node.next = node
else:
node = Node(item)
cur = self.__head
while cur.next != self.__head:
cur = cur.next
cur.next = node
node.next = self.__head
def insert(self, pos, item):
node = Node(item)
if pos <= 0:
self.add(item)
elif pos >= (self.length()-1):
self.append(item)
else:
cur = self.__head
count = 0
while count <= (pos - 2):
count += 1
cur = cur.next
node.next = cur.next
cur.next = node
def remove(self, item):
# 强行只用一个指针实现remove
# 首先判断是不是空链表
if self.is_empty():
return
cur = self.__head
# 如果要删除的元素是头结点
if cur.elem == item:
# 要找到尾节点指向新的头结点
while cur.next != self.__head:
cur = cur.next
# cur现在是尾节点
cur.next = self.__head.next # 这里不能搞乱顺序,不然可能会删不掉头结点
self.__head = cur.next
return
# 中间节点
while cur.next.next != self.__head:
# 不用两个指针就是这么麻烦,相当于要留下最后两个节点,把cur停在倒数第二个节点上。
# 因为如果停在最后一个节点,就没有指针留给你去删除最后一个节点了。
if cur.next.elem == item:
cur.next = cur.next.next
return
cur = cur.next
# 尾节点
# 因为留下尾部两个节点,所以要做两次判定
# 事实上用两个指针,更好懂,思路也更方便。
if cur.next.elem == item:
cur.next = cur.next.next
return
else:
cur = cur.next
if cur.next.elem == item:
cur.next = self.__head
return
print('没有要删除的数')
def search(self, item):
if self.is_empty():
return False
cur = self.__head
while cur.next != self.__head:
if cur.elem == item:
return True
else:
cur = cur.next
if cur.elem == item:
return True
return False
ll = SingleCycleLinkList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
ll.travel()
ll.add(10)
ll.travel()
ll.insert(3, 200)
ll.insert(-1,100)
ll.insert(20, 300)
ll.travel()
ll.remove(250)
ll.travel()
print(ll.search(250))
# 1 2 3 4 5
# 10 1 2 3 4 5
# 100 10 1 2 200 3 4 5 300
# 没有要删除的数
# 100 10 1 2 200 3 4 5 300
# False