看此部落格之前建議先看看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