国产探花免费观看_亚洲丰满少妇自慰呻吟_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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 德保县| 宜春市| 莱西市| 威海市| 名山县| 临桂县| 方城县| 柳州市| 新津县| 容城县| 灯塔市| 鞍山市| 吉安县| 双牌县| 达州市| 马尔康县| 册亨县| 上饶县| 静乐县| 中西区| 康马县| 丽江市| 凉城县| 潮安县| 麻阳| 富锦市| 白玉县| 清新县| 宁安市| 兰考县| 荥经县| 延安市| 四会市| 嘉兴市| 张北县| 保靖县| 郓城县| 息烽县| 前郭尔| 苗栗市| 南开区|