# coding:utf-8
class Node(object):
"""節點0"""
def __init__(self, elem):
self.elem = elem
self.next = None
# node = None(100)
class SingleCycleLinkList(object):
"""單向循環鏈表"""
def __init__(self, node=None):
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記錄數量
count = 1
while cur.next != self.__head:
count += 1
cur = cur.next
return count
def travel(self):
"""遍歷整個鏈表"""
cur = self.__head
while cur.next != self.__head:
print(cur.elem, end=" ")
cur = cur.next
# 退出循環, cur指向尾節點,但尾節點的元素未打印
print(cur.elem)
def add(self, item):
"""鏈表頭部添加元素,頭插法"""
node = Node(item)
if self.is_empty():
self.__head = node
node.next = node
else:
cur = self.__head
while cur.next != self.__head:
cur = cur.next
# 退出循環, cur指向尾節點
node.next = self.__head
self.__head = node
# cur.next = node
cur.next = self.__head
def append(self, item):
"""鏈表尾部添加元素,尾插法"""
node = Node(item)
if self.is_empty():
self.__head = node
node.next = node
else:
cur = self.__head
while cur.next != self.__head:
cur = cur.next
# node.next = cur.next
node.next = self.__head
cur.next = node
def insert(self, pos, item):
"""指定位置添加元素
:param pos 從0開始
"""
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
pre = self.__head
count = 0
while count < (pos-1):
count += 1
pre = pre.next
# 當循環退出後,pre指向pos-1位置
node = Node(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.elem == item:
# 先判斷此結點是否是頭節點
if cur == self.__head:
# 頭節點的情況
# 找尾節點
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.elem == 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.elem == item:
return True
else:
cur = cur.next
# 退出循環, cur指向尾節點
if cur.elem == item:
return True
return False
if __name__ == "__main__":
ll = SingleCycleLinkList()
print(ll.is_empty())
print(ll.length())
ll.append(1)
print(ll.is_empty())
print(ll.length())
ll.append(2)
ll.add(8)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
# 8 1 2 3 4 5 6
ll.insert(-1, 9) # 9 8 123456
ll.travel()
ll.insert(3, 100) # 9 8 1 100 2 3456
ll.travel()
ll.insert(10, 200) # 9 8 1 100 23456 200
ll.travel()
ll.remove(100)
ll.travel()
ll.remove(9)
ll.travel()
ll.remove(200)
ll.travel()
执行结果