- Python 資料結構與演算法教程
- Python - 資料結構首頁
- Python - 資料結構簡介
- Python - 資料結構環境
- Python - 陣列
- Python - 列表
- Python - 元組
- Python - 字典
- Python - 二維陣列
- Python - 矩陣
- Python - 集合
- Python - 對映
- Python - 連結串列
- Python - 棧
- Python - 佇列
- Python - 雙端佇列
- Python - 高階連結串列
- Python - 雜湊表
- Python - 二叉樹
- Python - 搜尋樹
- Python - 堆
- Python - 圖
- Python - 演算法設計
- Python - 分治法
- Python - 遞迴
- Python - 回溯法
- Python - 排序演算法
- Python - 搜尋演算法
- Python - 圖演算法
- Python - 演算法分析
- Python - 大O符號
- Python - 演算法類
- Python - 均攤分析
- Python - 演算法論證
- Python 資料結構與演算法實用資源
- Python - 快速指南
- Python - 實用資源
- Python - 討論
Python - 棧
在英語字典中,stack 這個詞的意思是將物體一個疊一個地排列。這種方式與這種資料結構中記憶體的分配方式相同。它以類似於廚房裡一堆盤子一個疊一個地存放的方式儲存資料元素。因此,棧資料結構允許在一端進行操作,這可以稱為棧的頂部。我們只能在這個棧的端點新增或刪除元素。
在棧中,最後插入的元素將首先出來,因為我們只能從棧頂刪除元素。這種特性被稱為後進先出 (LIFO) 特性。新增和刪除元素的操作被稱為PUSH和POP。在下面的程式中,我們將其實現為add和remove函式。我們宣告一個空列表,並使用append()和pop()方法新增和刪除資料元素。
進棧(PUSH)
讓我們瞭解一下如何在棧中使用PUSH。請參考下面提到的程式示例:
示例
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use peek to look at the top of the stack
def peek(self):
return self.stack[-1]
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
輸出
當執行上述程式碼時,會產生以下結果:
Tue Thu
出棧(POP)
正如我們所知,我們只能從棧中刪除最頂部的元素,我們實現了一個Python程式來做到這一點。下面的程式中的remove函式返回最頂部的元素。我們首先計算棧的大小來檢查頂部元素,然後使用內建的pop()方法找出最頂部的元素。
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use list pop method to remove element
def remove(self):
if len(self.stack) <= 0:
return ("No element in the Stack")
else:
return self.stack.pop()
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
輸出
當執行上述程式碼時,會產生以下結果:
Thu Wed
廣告