單向鏈表,只能從前往後遞進,單個節點只有後繼節點,沒有前驅節點
雙向鏈表,是一種既有後繼節點,又有前驅節點的鏈表結構
-
節點實現
class Node(object): def __init__(self, value): self.value = value self.next = None self.prev = None # 相較於單鏈表,多了一個前驅指針(爲了說明,python中沒有指針的概念)
-
雙向循環鏈表實現及常用方法
在雙鏈表中的方法的實現上,很多方法如is_empty、length、travel、search,其實現與單鏈表是相同的,可以實際用類繼承的方式來實現雙鏈表,這裏直接手動完成
class DoubleLinkList(object): def __init__(self): self.head = None def is_empty(self): '''判斷鏈表是否爲空(同單鏈表)''' return self.head == None def length(self): '''返回鏈表長度(同單)''' cur = self.head # 指針 count = 0 # 計數器 while cur != None: count += 1 cur = cur.next return count def travel(self): '''遍歷鏈表(同單)''' cur = self.head # 指針 while cur != None: print(cur.value, end=' ') cur = cur.next print() def add(self, value): '''頭部插入——頭插法''' node = Node(value) self.head.prev = node # 不同與單鏈表,加了.prev指針 node.next = self.head # 把新節點夾在head之前 self.head = node # 鏈表的新頭部編程node pass def append(self, value): '''尾部插入——尾插法''' node = Node(value) if self.is_empty(): self.head = node else: cur = self.head while cur.next != None: cur = cur.next cur.next = node node.prev = cur def insert(self, index, value): ''' :param index: the position of insert(start from 0) :param value: node.value :return: ''' node = Node(value) if index <= 0: self.add(value) elif index >= self.length(): self.append(value) else: cur = self.head count = 0 while count < index - 1: count += 1 cur = cur.next # 先操作node,不改變原有關係 node.next = cur.next node.prev = cur # 改變原來結構 cur.next.prev = node cur.next = node def remove(self, item): '''從鏈表中刪除item''' # 如果空鏈表 if self.head == None: return else: # 如果第一個就命中 if self.head.value == item: self.head = self.head.next else: cur = self.head while True: if cur.next != None: if cur.next.value == item: cur.next = cur.next.next if cur.next != None: cur.next.prev = cur break else: cur = cur.next else: break def search(self, item): '''在鏈表中查找item,含有返回True,不含返回False(因爲是鏈表,返回索引也沒有意義)''' cur = self.head while cur != None: cur = cur.next if cur.value == item: return True return False