當前位置:
首頁 >
数据结构链表之栈,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主要實現的功能:
功能驗證
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cv2.dnn.readNetFromD
- 下一篇: sublime text3c语言编译运行