python中的栈结构_python中有栈吗
在英語詞典中,堆(Stack)表示將對(duì)象放在另一個(gè)對(duì)象上。 在這個(gè)數(shù)據(jù)結(jié)構(gòu)中分配內(nèi)存的方式是一樣的。 它以類似的方式存儲(chǔ)數(shù)據(jù)元素,類似在廚房中一堆盤子:一個(gè)在另一個(gè)之上存放。 所以堆棧數(shù)據(jù)數(shù)據(jù)允許操作的一端可以稱為棧頂。 可在棧頂上添加元素或僅從堆棧中移除元素。
在堆棧中,順序排列的最后一個(gè)元素將首先出現(xiàn),因?yàn)橹荒軓亩褩m敳恳瞥?這種功能稱為后進(jìn)先出(LIFO)功能。 添加和刪除元素的操作稱為PUSH和POP。 在下面的程序中,我們將它實(shí)現(xiàn)為add和remove函數(shù)。首先聲明一個(gè)空列表并使用append()和pop()方法來添加和刪除數(shù)據(jù)元素。
推入堆棧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[0]AStack = Stack()AStack.add("Mon")AStack.add("Tue")AStack.peek()print(AStack.peek())AStack.add("Wed")AStack.add("Thu")print(AStack.peek())Python
執(zhí)行上面示例代碼,得到以下結(jié)果 -Mon
MonShell
相關(guān)推薦:《python視頻教程》
堆棧移除
只能從堆棧中移除數(shù)據(jù)元素,下面實(shí)現(xiàn)了一個(gè)可以實(shí)現(xiàn)這一功能的python程序。 以下程序中的remove函數(shù)返回最上面的元素。 首先通過計(jì)算堆棧的大小來檢查頂層元素,然后使用內(nèi)置的pop()方法找出最頂層的元素。參考以下代碼實(shí)現(xiàn)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")print(AStack.remove())AStack.add("Wed")AStack.add("Thu")print(AStack.remove())Python
執(zhí)行上面示例代碼,得到以下結(jié)果Tue
Thu
以上就是python中有棧嗎的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注Gxl網(wǎng)其它相關(guān)文章!
本條技術(shù)文章來源于互聯(lián)網(wǎng),如果無意侵犯您的權(quán)益請(qǐng)點(diǎn)擊此處反饋版權(quán)投訴
本文系統(tǒng)來源:php中文網(wǎng)
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python中的栈结构_python中有栈吗的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用未初始化的内存是什么意思_单根内存条
- 下一篇: 哪家不育医院好呢