Stacks and Queues
Queue from Two Stacks
Implement queue behavior with an input stack and an output stack.
Algorithm
Basic Implementation
basic.py
in_stack = []
out_stack = []
def enqueue(value):
in_stack.append(value)
def transfer():
while in_stack:
out_stack.append(in_stack.pop())
def dequeue():
if not out_stack:
transfer()
return out_stack.pop()
for value in [10, 20, 30]:
enqueue(value)
removed = [dequeue(), dequeue(), dequeue()]
print(" -> ".join(str(x) for x in removed))
Complexity
- Time: O(1) amortized per operation
- Space: O(n)
Implementation notes
- Python uses two plain lists,
in_stackandout_stack, as stacks. Enqueue isin_stack.append(value), and dequeue returnsout_stack.pop()from the end; nodequeis used in this lesson. - When
out_stackis empty,transfer()mutates both lists in awhile in_stackloop:in_stack.pop()removes the newest input value andout_stack.append(...)reverses the order for FIFO pops. Each value moves between stacks at most once before removal, giving the amortized behavior. - The stack lists and
removedresult list are the only persistent containers; normal Python GC owns them once no references remain. The trace shows[10, 20, 30]transfer to[30, 20, 10], then pop back out as[10, 20, 30].
input stack
Enqueue pushes new values onto the input stack.
output stack
When the output stack is empty, transferring all input values reverses them into dequeue order.