日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

数据结构链表之栈,Python3简单实现——5

發布時間:2024/7/5 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构链表之栈,Python3简单实现——5 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據結構鏈表之棧

棧的概述

  • 定義:棧是一種基于先進后出(FILO)的數據結構,是一種只能在一段進行插入和刪除操作的特殊線性表。
  • 引入名詞:將數據存入棧的動作稱為壓棧,將數據取出棧的動作稱為彈棧
  • 棧的特點:先進入棧的元素會被壓入棧底,最后一位元素所處的位置就是棧頂,彈棧時最后一個元素最先被讀取,依次往下取出,因此叫做First In Last Out

棧可以用順序表(python中列表)實現,也可以用鏈表實現,這里實現的方式的是使用鏈表,有興趣的同學可以自己編寫代碼用列表實現棧

python代碼實現:

class Node:def __init__(self, item):self.item = itemself.next = Noneclass Stack:def __init__(self):self.head = Noneself.len = 0def is_empty(self):return not self.len# def length(self):# return self.lendef push(self, item):"""Push an element into the stack"""node = Node(item)node.next = self.headself.head = nodeself.len += 1def pop(self):"""Pop a value from the stack top"""# if not self.head:# raise IndexError("pop from empty list")cur = self.headif self.head:self.head = self.head.nextself.len -= 1return cur# Make the Stack iterabledef __iter__(self):self.cur = self.head# if not self.cur:# raise StopIteration # The error here will be raised if the condition were reachedreturn selfdef __next__(self):if not self.cur:raise StopIteration # The error here actually won't be raisedtry:temp = self.curself.cur = self.cur.nextreturn tempexcept AttributeError as e:raise StopIteration

主要實現的功能:

  • is_empty()判斷棧是否為空
  • length()同len屬性,可以返回棧的長度
  • push()向棧壓入元素
  • pop()從棧頂取出一個元素
  • 重寫的__iter__()和__next__()用于實現棧的遍歷功能
  • 功能驗證

    if __name__ == "__main__":stack = Stack()print(f"Is empty? {stack.is_empty()}")print("Push elements into the stack:")stack.push('a')stack.push('b')stack.push('c')stack.push('d')# Iterate the stackfor item in stack:print(item.item, end=' ')print(f"\nPop a value from the top stack: {stack.pop().item}")print(f"The number(length) of the remanent nodes is: {stack.len}")

    輸出結果:

    Is empty? True Push elements into the stack: d c b a Pop a value from the top stack: d The number(length) of the remanent nodes is: 3

    總結

    以上是生活随笔為你收集整理的数据结构链表之栈,Python3简单实现——5的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。