這篇文章主要介紹了Python資料結構與演算法之鍊錶定義與用法,結合具體實例形式較為詳細的分析了單鍊錶、循環鍊錶等的定義、使用方法與相關注意事項,需要的朋友可以參考下
本文實例講述了Python資料結構與演算法之鍊錶定義與用法。分享給大家供大家參考,具體如下:
本文將為大家講解:
(1)從鍊錶節點的定義開始,以類別的方式,物件導向的想法進行鍊錶的設計
(2)鍊錶類別插入和刪除等成員函數實作時需要考慮的邊界條件,
prepend(頭部插入)、pop(頭部刪除)、append(尾部插入)、pop_last (尾部刪除)
2.1 插入:
空鍊錶
鍊錶長度為1
插入到結尾
2.2刪除
空鍊錶
鍊錶長度為1
刪除結束元素
(3)從單鍊錶到單鍊錶的一眾變體:
帶尾節點的單鍊錶
循環單鍊錶
雙鍊錶
#1. 鍊錶節點的定義
##
class LNode: def __init__(self, elem, next_=None): self.elem = elem self.next = next_
2. 單鍊錶的實作
重點理解插入、刪除的實作及其需要考慮的邊界條件:class LinkedListUnderflow(ValueError): pass class LList: def __init__(self): self._head = None def is_empty(self): return self._head is None def prepend(self, elem): self._head = LNode(elem, self._head) def pop(self): if self._head is None: raise LinkedListUnderflow('in pop') e = self._head.elem self._head = self._head.next return e def append(self, elem): if self._head is None: self._head = LNode(elem) return p = self._head while p.next is not None: p = p.next p.next = LNode(elem) def pop_last(self): if self._head is None: raise LinkedListUnderflow('in pop_last') p = self._head if p.next is None: e = p.elem self._head = None return e while p.next.next is not None: p = p.next e = p.next.elem p.next = None return e
簡單總結:
(0)能夠存取p.next.next 的前提是p.next 不為空;(1)尾部插入,如果鍊錶不為空,需且僅需改變的是尾部節點的指標;
(2)尾部刪除,如果鍊錶長度不為空,需且僅需改變的是倒數第二個節點的指標。
單鍊錶的簡單變形:具有尾部節點的單鍊錶
#
class LList1(LList): def __init__(self): LList.__init__(self) self._rear = None ...
頭部的插入、尾部的插入、尾部的刪除
def prepend(self, elem): if self._head is None: self._head = LNode(elem) self._rear = self._head else: self._head = LNode(elem, self._head) def append(self, elem): if self._head is None: self._head = LNode(elem) self._rear = self._head else: self._rear.next = LNode(elem) self._rear = self._rear.next def pop_last(self): if self._head is None: raise LinkedListUnderflow('in pop_last') p = self._head if p.next is None: e = p.elem self._head = None return e while p.next.next is not None: p = p.next e = p.next.elem self._rear = p p.next = None return e
單鍊錶的變體:循環單鍊錶
class LCList: def __init__(self): self._rear = None def prepend(self, elem): if self._rear is None: self._rear = LNode(elem) self._rear.next = self._rear else: self._rear.next = LNode(elem, self._rear.next) def append(self, elem): self.prepend(elem) self_rear = self._rear.next def pop(self): if self._rear is None: raise LinkedListUnderflow('in pop') p = self._rear.next if p is None: self._rear = None else: self._rear.next = p.next return p.elem def printall(self): if self._rear is None: raise ... p = self._rear.next while True: print(p.elem) if p is self._rear: break p = p.next
以上是Python資料結構與演算法之鍊錶定義的使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!