国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python中實現棧的三種方法

瀏覽:41日期:2022-07-01 17:09:14

棧是一種線性數據結構,用先進后出或者是后進先出的方式存儲數據,棧中數據的插入刪除操作都是在棧頂端進行,常見棧的函數操作包括

empty() ? 返回棧是否為空 ? Time Complexity : O(1) size() ? 返回棧的長度 ? Time Complexity : O(1) top() ? 查看棧頂元素 ? Time Complexity : O(1) push(g) ? 向棧頂添加元素 ? Time Complexity : O(1) pop() ? 刪除棧頂元素 ? Time Complexity : O(1)

python中??梢杂靡韵氯N方法實現:

1)list

2)collections.deque

3)queue.LifoQueue

使用列表實現棧

python的內置數據結構list可以用來實現棧,用append()向棧頂添加元素, pop() 可以以后進先出的順序刪除元素

但是列表本身有一些缺點,主要問題就是當列表不斷擴大的時候會遇到速度瓶頸.列表是動態數組,因此往其中添加新元素而沒有空間保存新的元素時,它會自動重新分配內存塊,并將原來的內存中的值復制到新的內存塊中.這就導致了一些append()操作會消耗更多的時間

>>> stack = []>>> #append() fuction to push... #element in list... >>> stack.append(’hello’)>>> stack.append(’world’)>>> stack.append(’!’)>>> print(’Initial stack’)Initial stack>>> print(stack)[’hello’, ’world’, ’!’]>>> #pop() function to pop element... #from stack in LIFO order... >>> print(’nElement poped from stack’)Element poped from stack>>> print(stack.pop())!>>> print(stack.pop())world>>> print(stack.pop())hello>>> print(’nStack after all elements are poped’)Stack after all elements are poped>>> print(stack)[]使用collections.deque實現棧

python中棧也可以用deque類實現,當我們想要在實現在容器兩端更快速地進行append和pop操作時,deque比列表更合適.deque可以提供O(1)時間的append和pop操作,而列表則需要O(n)時間.

>>> from collections import deque>>> stack = deque()>>> # append() fuction to push... #element in list... >>> stack.append(’hello’)>>> stack.append(’world’)>>> stack.append(’!’)>>> print(’Initial stack’)Initial stack>>> print(stack)deque([’hello’, ’world’, ’!’])>>> #pop() function to pop element... #from stack in LIFO order... >>> print(’nElement poped from stack’)Element poped from stack>>> print(stack.pop())!>>> print(stack.pop())world>>> print(stack.pop())hello>>> print(’nStack after all elements are poped’)Stack after all elements are poped>>> print(stack)deque([])使用queue module實現棧

Queue模塊有LIFO queue,也就是棧結構.用put()和get()操作從Queue中添加和獲得數據

>>> from queue import LifoQueue>>> stack = LifoQueue(maxsize = 3)>>> print(stack.qsize())0>>> stack.put(’hello’)>>> stack.put(’world’)>>> stack.put(’!’)>>> print(’nElement poped from stack’)Element poped from stack>>> print(stack.get())!>>> print(stack.get())world>>> print(stack.get())hello>>> print(’nEmpty:’, stack.empty())Empty: True

以上就是python中實現棧的三種方法的詳細內容,更多關于python 實現棧的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 炉霍县| 华阴市| 沙湾县| 丹阳市| 南汇区| 卢湾区| 潜江市| 上饶市| 江陵县| 通化市| 沿河| 建始县| 闵行区| 尼勒克县| 华容县| 玉树县| 蒲江县| 南和县| 新沂市| 丰顺县| 昭觉县| 前郭尔| 塘沽区| 南皮县| 禄劝| 五台县| 青河县| 竹溪县| 武陟县| 米易县| 天镇县| 株洲县| 阿勒泰市| 大冶市| 阿克陶县| 新丰县| 荥经县| 宁远县| 剑河县| 古浪县| 鸡西市|