class Node(object):
"单循环链表节点"
def __init__(self,item):
self.item=item
self.next=None
class singlecirclelist(object):
"""单循环链表"""
def __init__(self):
self._head=None
# is_empty() 判断链表是否为空
def is_empty(self):
cur=self._head
return cur is None
#链表长度
def length(self):
cur=self._head
if cur==None:#为空
count=0
return count
count=1
while cur.next!=self._head:#不为空
cur=cur.next
count+=1
return count
# 遍历输出
def printlist(self):
cur=self._head
if cur==None:
return
else:
while cur.next!=self._head:
print(cur.item)
cur=cur.next
print(cur.item)
# add(item) 在头部添加一个节点
def add(self,item):
node=Node(item)
cur=self._head
if cur==None:
self._head = node
node.next = self._head
return
else:
while cur.next!=self._head:
cur=cur.next
cur.next=node
node.next=self._head
self._head=node
# append(item) 在尾部添加一个节点
def append(self,item):
node = Node(item)
cur = self._head
if cur == None:
self._head = node
node.next = self._head
return
else:
while cur.next!=self._head:
cur=cur.next
cur.next=node
node.next=self._head
# 指定位置添加
def insert(self,pos,item):
if not isinstance(pos,int):
raise TypeError
if pos <= 0:#表头添加
self.add(item)
elif pos >= self.length():#表尾添加
self.append(item)
else:
cur=self._head
node=Node(item)
count=0
while count<pos-1:
count+=1
cur=cur.next
node.next=cur.next
cur.next=node
# remove(item) 删除一个节点
def remove(self,item):
cur = self._head
if cur==None:
return
pre = None
while cur.next != self._head:
if cur.item == item:
if cur == self._head:
rear = self._head
while rear.next != self._head:
rear = rear.next
# rear指向的就是尾部节点
rear.next = cur.next
self._head = cur.next
return
pre.next = cur.next
pre = cur
cur = cur.next
# cur指向的是尾部节点
if cur.item == item:
if cur == self._head:
self._head = None
return
pre.next = cur.next
# search(item) 查找节点是否存在
def search(self,item):
cur=self._head
if cur==None:
print(False)
return
while cur.next != self._head:
if cur.item==item:
print(True)
return
cur=cur.next
if cur.item==item:
print(True)
return
print(False)
return
if __name__=="__main__":
s=singlecirclelist()
s.add(1)
s.add(2)
s.add(3)
s.search(4)