python で キュー と スタック を扱う場合、通常の配列に append、pop を使えば処理できますが、処理速度を考えると collections の deque を使ったほうがいいようです。ちなみに deque の append、pop はスレッドセーフらしいです(deque オブジェクト)。
- 目次 -
スポンサーリンク
キュー
append で追加し、popleft で取りだします。
1 2 3 4 5 6 7 8 9 10 |
from collections import deque q = deque([]) q.append(1) q.append(2) q.append(3) while len(q) > 0: print q.popleft() |
結果
1 2 3 |
1 2 3 |
スタック
append で追加し、pop で取りだします。
1 2 3 4 5 6 7 8 9 10 |
from collections import deque q = deque([]) q.append(1) q.append(2) q.append(3) while len(q) > 0: print q.pop() |
結果
1 2 3 |
3 2 1 |