Implement Queue using Stacks
1 approach, code in every language
Problem description
Build a first-in-first-out (FIFO) queue whose entire internal storage is limited to standard stacks. A stack only exposes the usual last-in-first-out operations: push a value on top, pop the top value, look at the top value, and check whether it is empty.
Implement the class MyQueue with the following methods: push(x) adds element x to the back of the queue, pop() removes and returns the element at the front, peek() returns the front element without removing it, and empty() reports whether the queue currently holds no elements.
Your implementation may use one or more stacks, but you are not allowed to reach into the middle of any stack. Every access must go through the top of a stack.
Example 1
Input: operations = ["MyQueue", "push", "push", "peek", "pop", "empty"] args = [[], [1], [2], [], [], []]
Output: [null, null, null, 1, 1, false]
After pushing 1 then 2, peek returns the front element 1. pop removes and returns 1. The queue still holds 2, so empty is false.
Example 2
Input: operations = ["MyQueue", "push", "pop", "empty"] args = [[], [7], [], []]
Output: [null, null, 7, true]
A single element 7 is pushed and immediately popped, leaving the queue empty.
Constraints
1 <= x <= 9At most 100 calls will be made to push, pop, peek, and empty.All calls to pop and peek are valid: they are only made on a non-empty queue.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free