連結串列相關方法的實現
阿新 • • 發佈:2020-08-13
class Link(): def __init__(self): self._head = None # 頭節點 def travel(self): # 遍歷整個連結串列 cur = self._head while cur: print(cur.item) cur = cur.next def add(self, item): # 連結串列頭部插入節點 node = Node(item) node.next = self._head self._head = node def append(self, item): # 連結串列尾部追加節點 node = Node(item) if self._head is None: self._head = node return cur = self._head while cur.next: cur = cur.next cur.next = node def insert(self, pos, item): # 指定位置插入節點 node = Node(item) if pos > self.length(): return 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): # 刪除節點 pre = None cur = self._head if item == cur.item: self._head = cur.next return while cur: if cur.item == item: pre.next = cur.next break pre = cur cur = cur.next def reverse(self): # 連結串列的反轉 pre = None node = self._head ne_xt = node.next def is_empty(self): # 連結串列是否為空 return self._head is None def length(self): # 連結串列的長度 count = 0 cur = self._head while cur: count += 1 cur = cur.next return count def search(self, item): # 查詢節點是否存在 cur = self._head find = False while cur: if cur.item == item: find = True cur = cur.next return find