脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python中实现栈的三种方法

python中实现栈的三种方法

2021-08-16 00:10老张哈哈哈 Python

这篇文章主要介绍了python中实现栈的三种方法,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下

栈是一种线性数据结构,用先进后出或者是后进先出的方式存储数据,栈中数据的插入删除操作都是在栈顶端进行,常见栈的函数操作包括

  • 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中栈可以用以下三种方法实现:

1)list

2)collections.deque

3)queue.LifoQueue

使用列表实现栈

python的内置数据结构list可以用来实现栈,用append()向栈顶添加元素, pop() 可以以后进先出的顺序删除元素

但是列表本身有一些缺点,主要问题就是当列表不断扩大的时候会遇到速度瓶颈.列表是动态数组,因此往其中添加新元素而没有空间保存新的元素时,它会自动重新分配内存块,并将原来的内存中的值复制到新的内存块中.这就导致了一些append()操作会消耗更多的时间

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
>>> 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)时间.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>>> 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中添加和获得数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> 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 实现栈的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/laozhanghahaha/p/12302836.html

延伸 · 阅读

精彩推荐