class Node:
def __init__(self, elem):
self.elem = elem
self.next = None
class Single_cycle_link_list:
def __init__(self, node=None):
"""需要记录首节点的地址信息,所以需要创建一个私有类属性-头节点,
将节点和链表(Sing_link_list)进行连接
"""
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
else:
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
else:
cur = self.__head
while cur.next != self.__head:
print(cur.elem, end=" ")
cur = cur.next
print(cur.elem)
print("")
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
node.next = self.__head
self.__head = node
cur.next=node
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
cur.next = node
node.next=self.__head
def insert(self, pos, item):
"""在列表指定位置添加元素"""
pre = self.__head
node = Node(item)
count = 0
if pos <= 0:
self.add(item)
elif pos > self.length() - 1:
self.append(item)
else:
while count < (pos - 1):
count += 1
pre = pre.next
node.next = pre.next
pre.next = node
def remove(self, item):
"""列表剔除元素"""
if self.is_empty():
return
else:
cur=self.__head
pre=None
while cur.next !=self.__head:
if cur.elem==item:
if cur==self.__head:
real=self.__head
while real.next != self.__head:
real=real.next
self.__head=cur.next
real.next=cur.next
else:
pre.next=cur.next
return
else:
pre=cur
cur=cur.next
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
else:
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
if __name__ == "__main__":
li = Single_cycle_link_list()
print(li.is_empty())
print(li.length())
li.append(1)
print(li.is_empty())
print(li.length())
li.append(2)
li.append(3)
li.append(4)
li.append(5)
li.append(6)
li.add(7)
li.insert(-1, 80)
li.insert(0, 79)
li.insert(20, 100)
li.insert(3,0)
print("进行遍历")
li.travel()
li.remove(100)
li.travel()
li.remove(79)
li.travel()
li.remove(0)
li.travel()
print(li.search(5))
print(li.search(1000))