python中实现栈的三种方法
栈是一种线性数据结构,用先进后出或者是后进先出的方式存储数据,栈中数据的插入删除操作都是在栈顶端进行,常见栈的函数操作包括
- empty() –返回栈是否为空–TimeComplexity:O(1)
- size() – 返回栈的长度–TimeComplexity:O(1)
- top() –查看栈顶元素–TimeComplexity:O(1)
- push(g) –向栈顶添加元素–TimeComplexity:O(1)
- pop() –删除栈顶元素–TimeComplexity:O(1)
python中栈可以用以下三种方法实现:
1)list
2)collections.deque
3)queue.LifoQueue
使用列表实现栈
python的内置数据结构list可以用来实现栈,用append()向栈顶添加元素,pop()可以以后进先出的顺序删除元素
但是列表本身有一些缺点,主要问题就是当列表不断扩大的时候会遇到速度瓶颈.列表是动态数组,因此往其中添加新元素而没有空间保存新的元素时,它会自动重新分配内存块,并将原来的内存中的值复制到新的内存块中.这就导致了一些append()操作会消耗更多的时间
>>>stack=[]
>>>#append()fuctiontopush
...#elementinlist
...
>>>stack.append('hello')
>>>stack.append('world')
>>>stack.append('!')
>>>print('Initialstack')
Initialstack
>>>print(stack)
['hello','world','!']
>>>#pop()functiontopopelement
...#fromstackinLIFOorder
...
>>>print('\nElementpopedfromstack')
Elementpopedfromstack
>>>print(stack.pop())
!
>>>print(stack.pop())
world
>>>print(stack.pop())
hello
>>>print('\nStackafterallelementsarepoped')
Stackafterallelementsarepoped
>>>print(stack)
[]
使用collections.deque实现栈
python中栈也可以用deque类实现,当我们想要在实现在容器两端更快速地进行append和pop操作时,deque比列表更合适.deque可以提供O(1)时间的append和pop操作,而列表则需要O(n)时间.
>>>fromcollectionsimportdeque
>>>stack=deque()
>>>#append()fuctiontopush
...#elementinlist
...
>>>stack.append('hello')
>>>stack.append('world')
>>>stack.append('!')
>>>print('Initialstack')
Initialstack
>>>print(stack)
deque(['hello','world','!'])
>>>#pop()functiontopopelement
...#fromstackinLIFOorder
...
>>>print('\nElementpopedfromstack')
Elementpopedfromstack
>>>print(stack.pop())
!
>>>print(stack.pop())
world
>>>print(stack.pop())
hello
>>>print('\nStackafterallelementsarepoped')
Stackafterallelementsarepoped
>>>print(stack)deque([])
使用queuemodule实现栈
Queue模块有LIFOqueue,也就是栈结构.用put()和get()操作从Queue中添加和获得数据
>>>fromqueueimportLifoQueue
>>>stack=LifoQueue(maxsize=3)
>>>print(stack.qsize())
0
>>>stack.put('hello')
>>>stack.put('world')
>>>stack.put('!')
>>>print('\nElementpopedfromstack')
Elementpopedfromstack
>>>print(stack.get())
!
>>>print(stack.get())
world
>>>print(stack.get())
hello
>>>print('\nEmpty:',stack.empty())
Empty:True
以上就是python中实现栈的三种方法的详细内容,更多关于python实现栈的资料请关注毛票票其它相关文章!