python單向連結串列的基本實現與使用方法【定義、遍歷、新增、刪除、查詢等】
阿新 • • 發佈:2020-01-09
本文例項講述了python單向連結串列的基本實現與使用方法。分享給大家供大家參考,具體如下:
# -*- coding:utf-8 -*- #! python3 class Node(): def __init__(self,item): #初始化這個節點,值和下一個指向 self.item = item self.next = None class SingleLinklist(): def __init__(self): #初始化這個單鏈表的頭指標為空 self._head = None def length(self): #獲取這個連結串列的長度 count = 0 cur = self._head while cur != None: count+=1 cur = cur.next return count def is_empty(self): """判斷是否為空""" return self._head == None def add(self,item): """在頭部新增元素""" node = Node(item) node.next = self._head self._head = node def append(self,item): """在尾部新增元素""" cur = self._head node = Node(item) while cur != None: cur = cur.next cur.next = node def insert(self,pos,item): """在選定的位置新增元素""" cur = self._head node = Node(item) count = 0 if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: while count < (pos -1): count+=1 cur = cur.next node.next = cur.next cur.next = node def travel(self): """遍歷整個連結串列""" cur = self._head while cur != None: print(cur.item,end=" ") cur = cur.next print(" ") def remove(self,item): """刪除連結串列""" cur = self._head pre =None while cur != None: if cur.item == item: if not pre: self._head = cur.next break else: pre.next = cur.next else: pre = cur # cur = cur.next def search(self,item): """查詢某個節點""" cur = self._head while cur != None: if cur.item == item: print("找到這個元素了") return True cur = cur.next print("抱歉沒有這個元素") return False singlistdemo = SingleLinklist() singlistdemo.add(1) singlistdemo.add(2) singlistdemo.add(65) singlistdemo.insert(2,77) singlistdemo.insert(1,66) singlistdemo.insert(0,66) print(singlistdemo.length()) singlistdemo.travel() singlistdemo.remove(1) singlistdemo.travel() singlistdemo.search(65)
執行結果:
6
66 65 66 2 77 1
更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python資料結構與演算法教程》、《Python加密解密演算法與技巧總結》、《Python編碼操作技巧總結》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》及《Python入門與進階經典教程》
希望本文所述對大家Python程式設計有所幫助。