1. 程式人生 > >單迴圈連結串列

單迴圈連結串列

class Node():
def __init__(self,item):
self.item=item
self.next=None
class CycleSingleLinkList():
def __init__(self,node=None):
self.__head=node
def is_empty(self):
return self.__head is None
def length(self):
if self.is_empty():
return 0
count=1
cur=self.__head
while cur.next is not self.__head:
count+=1
cur=cur.next
return count
def travel(self):
if self.is_empty():
print('')
return
cur=self.__head
while cur.next is not self.__head:
print(cur.item,end='')
cur=cur.next
print(cur.item)
def search(self,item):
if self.is_empty():
return False
cur=self.__head
while cur.next is not self.__head:
if cur.item==item:
return True
cur=cur.next
if cur.item==item:
return True
return False
def add(self,item):
node=Node(item)
if self.is_empty():
self.__head=node
node.next=self.__head
cur=self.__head
while cur.next is not self.__head:
cur=cur.next
cur.next=node
node.next=self.__head
self.__head=node
def append(self,item):
node=Node(item)
if self.is_empty():
self.__head = node
node.next=self.__head
cur=self.__head
while cur.next is not 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():
self.append(item)
else:
cur=self.__head
count=0
while count<(pos-1):
cur=cur.next
count+=1
node.next=cur.next
cur.next=node
def remove(self,item):
if self.is_empty():
return
cur=self.__head
pre=None
while cur.next is not self.__head:
if cur.item==item:
if cur==self.__head:
tnode=self.__head
while tnode.next is not self.__head:
tnode=tnode.next
self.__head=cur.next
tnode.next=self.__head
else:
pre.next=cur.next
return
pre=cur
cur=cur.next
if cur.item==item:
if cur==self.__head:
self.__head=None
else:
pre.next=self.__head

if __name__ == '__main__':
cc=CycleSingleLinkList()
for i in range(10):
cc.append(i)
cc.travel()
print(cc.length())
cc.add(1)
cc.travel()
cc.insert(2,3)
cc.travel()
cc.remove(3)
cc.travel()