Implement Stack using Queues
1 approach, code in every language
Problem description
Build a last-in-first-out (LIFO) stack whose entire internal storage is limited to standard queues. A queue only exposes first-in-first-out operations: enqueue a value at the back, dequeue the value at the front, peek at the front value, and check whether it is empty.
Implement the class MyStack with the following methods: push(x) adds element x to the top of the stack, pop() removes and returns the element on top, top() returns the top element without removing it, and empty() reports whether the stack currently holds no elements.
You may use one or more queues, but you may only interact with them through their standard queue operations.
Example 1
Input: operations = ["MyStack", "push", "push", "top", "pop", "empty"] args = [[], [1], [2], [], [], []]
Output: [null, null, null, 2, 2, false]
After pushing 1 then 2, the top is 2. pop removes and returns 2, leaving 1 in the stack so empty is false.
Example 2
Input: operations = ["MyStack", "push", "pop", "empty"] args = [[], [5], [], []]
Output: [null, null, 5, true]
A single element 5 is pushed then popped, so the stack ends up empty.
Constraints
1 <= x <= 9At most 100 calls will be made to push, pop, top, and empty.All calls to pop and top are valid: they are only made on a non-empty stack.
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