python列表实现堆栈队列

list方法可以很容易地将列表用作堆栈,其中添加的最后一个元素是检索到的第一个元素(“last-in,first-out”)。要将项添加到堆栈顶部,请使用append()。要从堆栈顶部检索项目,请在pop()没有显式索引的情况下使用。例如:

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
[3, 4, 5, 6, 7]

stack.pop()
7

stack
[3, 4, 5, 6]

stack.pop()
6

stack.pop()
5

stack
[3, 4]

使用列表作为队列,其中添加的第一个元素是检索的第一个元素(“先进先出”); 但是,列表不能用于此目的。虽然列表末尾的追加和弹出很快,但是从列表的开头进行插入或弹出是很慢的(因为所有其他元素都必须移动一个)。

要实现队列,请使用collections.deque设计为具有快速追加和从两端弹出的队列。例如:

from collections import deque
queue = deque([“Eric”, “John”, “Michael”])
queue.append(“Terry”) # Terry arrives
queue.append(“Graham”) # Graham arrives
queue.popleft() # The first to arrive now leaves
‘Eric’

queue.popleft() # The second to arrive now leaves
‘John’

queue # Remaining queue in order of arrival
deque([‘Michael’, ‘Terry’, ‘Graham’])

猜你喜欢

转载自blog.csdn.net/zhang_sir_xia_sir/article/details/83018952