本文以實例形式展示了Python算法中棧(stack)的實現,對于學習數據結構域算法有一定的參考借鑒價值。具體內容如下:
1.棧stack通常的操作:
Stack() 建立一個空的棧對象
push() 把一個元素添加到棧的最頂層
pop() 刪除棧最頂層的元素,并返回這個元素
peek()? 返回最頂層的元素,并不刪除它
isEmpty()? 判斷棧是否為空
size()? 返回棧中元素的個數
2.簡單案例以及操作結果:
Stack Operation Stack Contents Return Value s.isEmpty() [] True s.push(4) [4] s.push('dog') [4,'dog'] s.peek() [4,'dog'] 'dog' s.push(True) [4,'dog',True] s.size() [4,'dog',True] 3 s.isEmpty() [4,'dog',True] False s.push(8.4) [4,'dog',True,8.4] s.pop() [4,'dog',True] 8.4 s.pop() [4,'dog'] True s.size() [4,'dog'] 2
這里使用python的list對象模擬棧的實現,具體代碼如下:
#coding:utf8 class Stack: """模擬棧""" def __init__(self): self.items = [] def isEmpty(self): return len(self.items)==0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if not self.isEmpty(): return self.items[len(self.items)-1] def size(self): return len(self.items) s=Stack() print(s.isEmpty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size())
感興趣的讀者可以動手測試一下本文所述實例代碼,相信會對大家學習Python能有一定的收獲。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
