python資料結構之棧、佇列的實現

yupeng發表於2013-11-08

這個在官網中list支援,有實現。

補充一下棧,佇列的特性:

1.棧(stacks)是一種只能通過訪問其一端來實現資料儲存與檢索的線性資料結構,具有後進先出(last in first out,LIFO)的特徵

2.佇列(queue)是一種具有先進先出特徵的線性資料結構,元素的增加只能在一端進行,元素的刪除只能在另一端進行。能夠增加元素的佇列一端稱為隊尾,可以刪除元素的佇列一端則稱為隊首。

地址在 http://docs.python.org/2/tutorial/datastructures.html#more-on-lists ,下面的官方的程式碼。

關於棧
>>>
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]

關於佇列
>>> 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'])

上面程式碼很清晰的解釋了上面的2種結構



 

相關文章