面向物件之Python的連結串列實現(二)迴圈連結串列
阿新 • • 發佈:2019-01-06
接上一章的練習,這裡接著實現單鏈表的變型——傳說中的迴圈單鏈表。給出一個簡單的類,構造4個功能並例項化測試。
在下一篇文章中將會關注一個比較tricky的問題:如何判斷連結串列有環?以及求出環長度
# -*- coding: utf-8 -*- """ Created on Wed Jan 24 21:14:29 2018 @author: Administrator """ from __future__ import print_function from lingkingtables import Lnode from lingkingtables import Llist from lingkingtables import LinkListUnderFlow #Python資料結構之迴圈單鏈表 #增加了尾結點,使得尾部查詢更優化,且便於迴圈的實現 #頭結點由_tail._next隱式說明,不單獨構造 class Clist: def __init__(self): self._tail = None #定義一個尾結點 def is_empty(self): return self._tail is None def prepend(self, value): #前端插入 p = Lnode(value) if self._tail is None: p._next = p #利用連結串列指標p判斷空連結串列 self._tail = p #如果為空則插入並令P為尾結點 else: p._next = self._tail._next self._tail._next = p def append(self, value): # self.prepend(value) self._tail = self._tail._next #直接在尾部之後插入並將尾節點後移一位,相當於在後端插入 def pop(self): if self._tail is None: raise LinkListUnderFlow("in pop of Clist") p = self._tail._next if self._tail is p: #只有一個節點時彈出後表為空 self._tail = None else: self._tail._next = p.value return p.value def printall(self): #列印所有連結串列元素 if self.is_empty(): return p = self._tail._next #通過指標p從頭結點開始 while p: print(p.value) if p is self._tail: break p = p._next #Ins例項化測試 Ins2 = Clist() Ins2.prepend(99) print(" test is commit... ") for i in range(1,21): Ins2.append(int(i)) Ins2.printall()
輸出如下:
[output]1:test is commit...
[output]2: 99
[output]3:1 2 3 4 5 6 7 8 9 10
[output]4:11 12 13 14 15 16 17 18 1920