看此博客之前建議先看看B站的視頻python數(shù)據(jù)結(jié)構(gòu)與算法系列課程,該課程中未實(shí)現(xiàn)雙向循環(huán)鏈表的操作,所以我按照該視頻的鏈表思路實(shí)現(xiàn)了雙向循環(huán)鏈表的操作,歡迎大家閱讀與交流,如有侵權(quán),請(qǐng)聯(lián)系博主!
下面附上代碼:
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): """鏈表長(zhǎng)度""" 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)插入, 下標(biāo)從0數(shù)起""" 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): """刪除某一節(jié)點(diǎn),若有多個(gè)符合條件的節(jié)點(diǎn),刪除第一個(gè)即可""" 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): """查找某一個(gè)節(jié)點(diǎn)""" 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中處理不到尾節(jié)點(diǎn),所以進(jìn)行最后尾節(jié)點(diǎn)的判斷 if cur.elem == elem: return True return False