国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Python > 正文

python單向鏈表的基本實現與使用方法【定義、遍歷、添加、刪除、

2024-09-09 19:02:16
字體:
來源:轉載
供稿:網友

本文實例講述了python單向鏈表的基本實現與使用方法。分享給大家供大家參考,具體如下:

# -*- coding:utf-8 -*-#! python3class Node():  def __init__(self,item):    #初始化這個節點,值和下一個指向    self.item = item    self.next = Noneclass 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 Falsesinglistdemo = 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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西平县| 浦县| 资兴市| 隆安县| 称多县| 五峰| 绥中县| 凤台县| 会理县| 棋牌| 平昌县| 东辽县| 汉寿县| 阿克苏市| 灌南县| 龙游县| 逊克县| 新竹市| 镇原县| 博兴县| 大同县| 衡阳市| 突泉县| 贵南县| 乌恰县| 炉霍县| 雷波县| 囊谦县| 深水埗区| 宜城市| 龙胜| 德昌县| 犍为县| 施甸县| 乳山市| 衡阳县| 沙坪坝区| 唐山市| 五大连池市| 张掖市| 民和|