python資料結構與演算法(8)
阿新 • • 發佈:2018-11-28
連結串列與順序表的對⽐
連結串列失去了順序表隨機讀取的優點,同時連結串列由於增加了結點的指標域,空 間開銷⽐較⼤,但對儲存空間的使⽤要相對靈活。
連結串列與順序表的各種操作複雜度如下所示:
注意雖然表⾯看起來複雜度都是 O(n),但是連結串列和順序表在插⼊和刪除時進 ⾏的是完全不同的操作。連結串列的主要耗時操作是遍歷查詢,刪除和插⼊操作 本身的複雜度是O(1)。順序表查詢很快,主要耗時的操作是拷⻉覆蓋。因為 除了⽬標元素在尾部的特殊情況,順序表進⾏插⼊和刪除時需要對操作點之 後的所有元素進⾏前後移位操作,只能通過拷⻉和覆蓋的⽅法進⾏。
雙向連結串列
⼀種更復雜的連結串列是“雙向連結串列”或“雙⾯連結串列”。每個節點有兩個連結:⼀個指 向前⼀個節點,當此節點為第⼀個節點時,指向空值;⽽另⼀個指向下⼀個 節點,當此節點為最後⼀個節點時,指向空值。
操作
is_empty() 連結串列是否為空 length() 連結串列⻓度 travel() 遍歷連結串列 add(item) 連結串列頭部新增 append(item) 連結串列尾部新增 insert(pos, item) 指定位置新增 remove(item) 刪除節點 search(item) 查詢節點是否存在
實現
class Node(object): """雙向連結串列節點""" def __init__(self, item): self.item = item self.next = None self.prev = None class DLinkList(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.item, cur = cur.next print "" def add(self, item): """頭部插⼊元素""" node = Node(item) if self.is_empty(): # 如果是空連結串列,將_head指向node self.__head = node else: # 將node的next指向_head的頭節點 node.next = self.__head # 將_head的頭節點的prev指向node self.__head.prev = node # 將_head 指向node self.__head = node def append(self, item): """尾部插⼊元素""" node = Node(item) if self.is_empty(): # 如果是空連結串列,將_head指向node self.__head = node else: # 移動到連結串列尾部 cur = self.__head while cur.next != None: cur = cur.next # 將尾節點cur的next指向node cur.next = node # 將node的prev指向cur node.prev = cur def search(self, item): """查詢元素是否存在""" cur = self.__head while cur != None: if cur.item == item: return True cur = cur.next return False