Skip to content
StackDecode
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

  1. A queue is first-in-first-out; a stack is last-in-first-out. Two stacks reverse the order twice.
  2. enqueue: push onto the input stack.
  3. dequeue: if the output stack is empty, pour the whole input stack into it (this reverses the order). Then pop from the output stack.
  4. Each item is moved at most once, so operations are O(1) amortised.

Watch it run

Loading animation…