Queue Using Two Stacks
Enqueue onto an in stack. When the out stack is empty, pour everything across to reverse the order.
Queue: Queue from two stacks
dequeue: the out stack is empty, so the front of the queue is buried at the bottom of in. Pour: pop every item off in and push it onto out, 5, 3, 9 in that order, which puts 5, the oldest, on top of out.
Cost
- Best
- O(1)
- Average
- O(1) amortized
- Worst
- O(n)
- Space
- O(n)
Before this
Related
Taught by the same lesson
Queue covers these too, in the same run.