定义
单向循环列表类似于单链表. 就是在单链表的尾部指向首结点
代码实现
结点的实现
class Node(object):
'''结点'''
def __init__(self, item):
self.item = item #item存放数据元素
self.next = None # next是下一个节点的标识
class SinCycLibk(object):
'''单向循环链表'''
# 空的单链表 self.__head = None
# 非空的单链表 node.next = node
def __init__(self, node=None): #判断是否是空链表
self.__head = node
if node:
node.next = node
is_empty判空
def is_empty(self):
return self.__head == None
lenght长度
def lenght(self):
cur = self.__head #游标指向头
if self.is_empty(): #判断是否为空,若不判断, 下面的next就报错
return 0
count = 1 #因为最后一次循环进不去下面的循环,所以从1开始
while cur.next != self.__head: #最后的尾结点指向头结点
count += 1
cur = cur.next #往下走
return count
travel遍历
def travel(self): #与求长度类似
if self.is_empty(): #若不判断, 下面的next就报错
return None
cur = self.__head
while cur.next != self.__head:
print(cur.item, end=' ')
cur = cur.next
# print('')
print(cur.item)
append尾部添加
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移动到最后
cur.next = node
node.next = self.__head #再把尾部添加的结点指向头结点
add头部添加
def add(self, item):
node = Node(item)
if s.is_empty(): #先判断是否为空
self.__head = node #直接添加node
node.next = self.__head #在把他指向自己
else:
cur = self.__head
while cur.next != self.__head:
cur = cur.next #游标继续往后移动,cur移到最后一个
node.next = self.__head #先把添加头结点与后面一个接上
self.__head = node #在把第一个头的位置给新添加的node
cur.next = node #末尾的结点指向头部添加的结点
insert 指定位置插入
def insert(self, pos, item):
if pos<0: #头部插入
self.add(item)
elif pos>self.lenght()-1: #尾部插入
self.append(item)
else:
node = Node(item)
cur = self.__head
count = 0
while count < pos-1: #使cur停在要插入的前一个
count+=1
cur = cur.next
node.next = cur.next
cur.next = node
search查找
def search(self, item):
if self.is_empty():
return
cur = self.__head
while cur.next != self.__head:
if cur.item == item:
return True
else:
cur = cur.next
if cur.item == item: # 循环退出 cur指向尾节点
return True
return False
remove删除
def remove(self, item):
if self.is_empty():
return
cur = self.__head
pre = None
#如果删除的就是头结点且不止一个结点
if cur.item == item: #删除的是头结点
if cur.next != self.__head: #不止一个结点
while cur.next != self.__head: #循环找到最后一个结点
cur = cur.next
cur.next = self.__head.next
self.__head = cur.next
else:
self.__head = None
else: #删除的不是第一个结点
while cur.next != self.__head:
if cur.item == item: #循环里面找到并且删除
pre.next = cur.next
return
else: #游标继续往下走
pre = cur
cur = cur.next
if cur.item == item: #如果删除的是最后一个结点
pre.next = cur.next
测试
s = SinCycLibk()
s.append(12)
s.append(13)
s.append(4)
s.insert(2, 100)
s.remove(100)
# print(s.search(20))
# s.add(34)
s.travel()
# print(s.is_empty())
# print(s.lenght())