The problem. Implement a first-in-first-out queue using only two stacks. Your class MyQueue must support push(x) (add x at the back), pop() (remove and return the front item), peek() (return the front item) and empty(). You may only use standard stack operations: push to the top, look at or pop the top, size and is-empty. pop and peek are only called when the queue isn't empty.
push(1) push(2) peek() -> 1 pop() -> 1 empty() -> falseA stack hands back its newest item; a queue must hand back its oldest. The one tool we have is in the picture above: pouring a stack into another reverses it, which brings the oldest item to the top.
In JavaScript a plain array is a perfect stack — push and pop both work at the end in O(1) — so there's no hidden cost here.
Free account
Sign up to read the rest of this lesson: 7 more sections, 4 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come
Was this helpful?