python 資料結構與演算法 day02 單向迴圈連結串列
阿新 • • 發佈:2018-11-07
1. 實現單向迴圈連結串列
class Node(): """定義結點""" def __init__(self,item): self.item=item self.next=None class SingleLoopLinkList(object): """單向迴圈連結串列""" def __init__(self,node=None): self.__head=node if node: # 如果把一個節點掛到單向迴圈連結串列的鏈子中,需要指向自身(構成一個迴圈) node.next=nodedef is_empty(self): """判斷單向迴圈連結串列是否為空""" if self.__head is None: return True return False def length(self): """求單鏈表的長度""" count=1 cur=self.__head while cur.next is not self.__head: count+=1 cur=cur.nextreturn count def travel(self): """單向迴圈連結串列的遍歷""" cur=self.__head while cur.next is not self.__head: print(cur.item,end=" ") cur=cur.next print(cur.item,end=" ") print(" ") def add(self,item): """單向迴圈連結串列頭部新增元素""" node=Node(item) cur=self.__head if cur is None: self.__head=node node.next=self.__head else: while cur.next is not self.__head: cur=cur.next node.next=self.__head self.__head=node cur.next=node def append(self,item): """單向迴圈連結串列尾部追加元素""" node=Node(item) cur=self.__head if cur is None: self.__head=node node.next=self.__head else: while cur.next is not self.__head: cur=cur.next cur.next=node node.next=self.__head def insert(self,pos,item): """單向迴圈連結串列指定位置插入元素""" count=0 node=Node(item) cur=self.__head if pos<=0: self.add(item) elif pos>=self.length(): self.append(item) else: while count<pos-1: cur=cur.next count+=1 node.next=cur.next cur.next=node def search(self,item): """判斷單向迴圈連結串列是否存在某一個元素""" 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 remove(self,item): """單向迴圈連結串列刪除某一個元素""" if self.search(item): pre=None cur=self.__head while cur.next is not self.__head: if cur.item==item: if cur ==self.__head: pre=cur.next while cur.next is not self.__head: cur=cur.next cur.next=pre self.__head=pre else: pre.next=cur.next break else: pre=cur cur=cur.next if cur.item==item: pre.next=self.__head if __name__=="__main__": slll=SingleLoopLinkList() print(slll.is_empty()) slll.add(10000000) slll.append(1) slll.append(2) slll.append(3) slll.append(4) slll.add(0) print(slll.length()) slll.travel() slll.insert(0,1000) slll.insert(2,3000) slll.insert(20,2000) slll.travel() slll.remove(1000) slll.remove(2000) slll.travel()
執行結果: