您好,登錄后才能下訂單哦!
看此博客之前建議先看看B站的視頻python數據結構與算法系列課程,該課程中未實現雙向循環鏈表的操作,所以我按照該視頻的鏈表思路實現了雙向循環鏈表的操作,歡迎大家閱讀與交流,如有侵權,請聯系博主!
下面附上代碼:
class Node: def __init__(self, elem): self.elem = elem self.prev = None self.next = None class DoubleCycleLinkList: def __init__(self, node=None): self.__head = node def is_empty(self): """判空""" if self.__head is None: return True return False def length(self): """鏈表長度""" if self.is_empty(): return 0 cur = self.__head count = 1 while cur.next is not self.__head: count += 1 cur = cur.next return count def travel(self): """遍歷鏈表""" if self.is_empty(): return cur = self.__head while cur.next is not self.__head: print(cur.elem, end=" ") cur = cur.next print(cur.elem, end=" ") print("") def add(self, elem): """頭插法""" node = Node(elem) if self.is_empty(): self.__head = node node.prev = node node.next = node else: self.__head.prev.next = node node.prev = self.__head.prev node.next = self.__head self.__head.prev = node self.__head = node def append(self, elem): """尾插法""" node = Node(elem) if self.is_empty(): self.__head = node node.prev = node node.next = node else: node.next = self.__head node.prev = self.__head.prev self.__head.prev.next = node self.__head.prev = node def insert(self, pos, elem): """任一位置(pos)插入, 下標從0數起""" if pos <= 0: self.add(elem) elif pos > (self.length() - 1): self.append(elem) else: count = 0 cur = self.__head node = Node(elem) while count < (pos - 1): count += 1 cur = cur.next node.next = cur.next node.prev = cur node.next.prev = node cur.next = node def remove(self, elem): """刪除某一節點,若有多個符合條件的節點,刪除第一個即可""" if self.is_empty(): return cur = self.__head while cur.next is not self.__head: if cur.elem == elem: if cur is self.__head: self.__head = cur.next cur.prev.next = cur.next cur.next.prev = cur.prev else: cur.prev.next = cur.next cur.next.prev = cur.prev break cur = cur.next if cur.elem == elem: cur.prev.next = self.__head self.head = cur.prev def search(self, elem): """查找某一個節點""" if self.is_empty(): return False cur = self.__head while cur.next is not self.__head: if cur.elem == elem: return True cur = cur.next # while中處理不到尾節點,所以進行最后尾節點的判斷 if cur.elem == elem: return True return False
到此這篇關于python實現數據結構中雙向循環鏈表操作的示例的文章就介紹到這了,更多相關python 雙向循環鏈表操作內容請搜索億速云以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持億速云!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。