python建立迴圈單鏈表
阿新 • • 發佈:2020-09-16
使用python建立迴圈單鏈表程式碼如下:
# coding:utf-8 class Node(object): """節點""" def __init__(self, elem): self.elem = elem self.next = None class SingleCycleLinkList(object): """單向迴圈連結串列""" def __init__(self, node=None): self.__head = node if node: node.next=node def is_empty(self): """連結串列是否為空""" return self.__head == None def length(self): """連結串列長度""" # cur遊標,用來移動遍歷節點 if self.is_empty(): return 0 cur = self.__head # count記錄數量 count = 1#計數從1,因為依據下述的迴圈條件,cur走到尾節點時不進入迴圈,此時count值不包含尾節點while cur.next != self.__head: count += 1 cur = cur.next return count def travel(self): """遍歷整個連結串列""" if self.is_empty(): return cur = self.__head #若連結串列為空,則cur.next不存在,迴圈會出問題,故先判斷是否為空連結串列 while cur.next !=self.__head: print(cur.elem, end=" ") cur = cur.next #當cur指向尾節點時即退出迴圈,故尾節點此時並未進行列印,下述語句列印尾節點 print(cur.elem) def add(self, item): """連結串列頭部新增元素,頭插法""" node = Node(item) #先判斷連結串列是否為空,若為空執行if內語句 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語句 if self.is_empty(): self.__head = node node.next=self.__head else: #連結串列不為空 cur = self.__head while cur.next != self.__head: cur = cur.next node.next=cur.next cur.next=node def insert(self, pos, item): """指定位置新增元素 :param pos 從0開始 """ node = Node(item) if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: #從中間部分插入與單鏈表一致,故無需進行改變 pre = self.__head count = 0 while count < (pos-1): count += 1 pre = pre.next # 當迴圈退出後,pre指向pos-1位置 node.next = pre.next pre.next = node def remove(self, item): """刪除節點""" cur = self.__head pre = None if self.is_empty(): #判斷連結串列是否為空 self.__head=None return while cur.next!=self.__head: #遍歷連結串列 if cur.elem == item: # 先判斷cur是否等於item if cur == self.__head: # 判斷相等的節點是否是頭節點 #刪除頭節點,先增加一個遊標mov指向尾節點 mov=self.__head while mov.next!=self.__head: mov=mov.next self.__head=cur.next mov.next=self.__head else:#中間節點 pre.next=cur.next return else: pre = cur cur = cur.next #跳出迴圈,cur指向尾節點 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__": ll = SingleCycleLinkList() print(ll.is_empty()) print(ll.length()) ll.append(1) print(ll.is_empty()) print(ll.length()) ll.append(2) ll.travel() ll.add(8) ll.travel() ll.append(3) ll.add(4) ll.append(5) ll.insert(-1, 9) ll.travel() ll.insert(3, 100) ll.travel() ll.insert(10, 200) ll.travel() ll.remove(100) ll.travel() ll.remove(9) ll.travel() ll.remove(200) ll.travel() print(ll.search(8))
執行輸出:
參考學習視訊:https://www.bilibili.com/video/BV18W411T7Vv?p=16