鏈表是一種物理存儲單元上非連續、非順序的存儲結構,數據元素的邏輯順序是經過鏈表中的指針連接次序實現的。鏈表由一系列結點(鏈表中每個元素稱爲結點)組成,結點能夠在運行時動態生成。每一個結點包括兩個部分:一個是存儲數據元素的數據域,另外一個是存儲下一個結點地址的指針域。 相比於線性表順序結構,操做複雜。因爲沒必要須按順序存儲,鏈表在插入的時候能夠達到O(1)的複雜度,比另外一種線性表順序錶快得多,可是查找一個節點或者訪問特定編號的節點則須要O(n)的時間,而線性表和順序表相應的時間複雜度分別是O(logn)和O(1)。node
class Node(object): """ 封裝節點 """ def __init__(self, item): # 存儲數據元素的數據域 self.item = item # 存儲下一個結點地址的指針域 self.next = None class Link(object): """ 封裝鏈表 """ def __init__(self): # 初始化一個空鏈表 self._head = None # '_head' 用於指向鏈表的第一個節點 def add(self, item): """ 鏈表首部插入節點 :param item: :return: """ node = Node(item) node.next = self._head self._head = node def travel(self): """ 遍歷每個節點 :return: """ cur = self._head while cur: print(cur.item) cur = cur.next def length(self): """ 鏈表中節點的個數 :return: """ count_node = 0 cur = self._head while cur: count_node += 1 cur = cur.next return count_node def isEmpty(self): """ 判斷鏈表是否爲空 :return: """ return self._head == None def search(self, item): """ 查找是否存在item對應的節點 :param item: :return: """ find = False cur = self._head while cur: if cur.item == item: find = True break else: cur = cur.next return find def append(self, item): """ 鏈表的尾部插入節點 :param item: :return: """ node = Node(item) if self._head == None: self._head = node return cur = self._head pre = None while cur: pre = cur cur = cur.next pre.next = node def insert(self, pos, item): """ 鏈表中指定的位置插入新的節點 :param pos: :param item: :return: """ node = Node(item) if pos == 0: node.next = self._head self._head = node return pre = None cur = self._head for i in range(pos): pre = cur cur = cur.next pre.next = node node.next = cur def remove(self, item): """ 刪除節點 :param item: :return: """ cur = self._head pre = None if cur.item == item: self._head = cur.next return while True: pre = cur cur = cur.next if cur.item == item: pre.next = cur.next break if cur == None: break def reverse(self): """ 鏈表倒置 :return: """ pre = None cur = self._head next_node = cur.next while cur: cur.next = pre pre = cur cur = next_node if cur != None: next_node = next_node.next self._head = pre self.travel() if __name__ == '__main__': link = Link() link.append(1) link.append(2) link.append(3) link.append(4) link.reverse() # 4 # 3 # 2 # 1