Stacks & queuesAnimated
Queue Using Stacks
An input stack and an output stack reverse the order twice.
Time
O(1) amortised
Extra space
O(n)
Use it for
Implementing FIFO with LIFO parts.
How it works
- A queue is first-in-first-out; a stack is last-in-first-out. Two stacks reverse the order twice.
- enqueue: push onto the input stack.
- dequeue: if the output stack is empty, pour the whole input stack into it (this reverses the order). Then pop from the output stack.
- Each item is moved at most once, so operations are O(1) amortised.
Watch it run
Loading animation…