1. 程式人生 > >python列表實現堆疊佇列

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’])