← All problems

225. Implement Stack Using Queues

EasyOpen on LeetCodeProblem statement

Problem Statement

225. Implement Stack using Queues

Easy


Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

Notes:

 

Example 1:

Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

 

Constraints:

 

Follow-up: Can you implement the stack using only one queue?

Java

Source file
class MyStack {
    Queue<Integer> q1 = new LinkedList<>();
    Queue<Integer> q2 = new LinkedList<>();

    public MyStack() {

    }

    public void push(int x) {
        while (!q1.isEmpty())
            q2.offer(q1.poll());
        q1.offer(x);
        while (!q2.isEmpty())
            q1.offer(q2.poll());
    }

    public int pop() {
        // if (q1.isEmpty())    // because constraints mention always valid
        //     return -1;
        return q1.poll();
    }

    public int top() {
        return q1.peek();
    }

    public boolean empty() {
        return q1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */