MrainW's Home

All things come to those who wait!

0%

LeetCode 225. Implement Stack using Queues

Question

  • 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:

    • void push(int x) Pushes element x to the top of the stack.
    • int pop() Removes the element on the top of the stack and returns it.
    • int top() Returns the element on the top of the stack.
    • boolean empty() Returns true if the stack is empty, false otherwise.

https://leetcode.com/problems/implement-stack-using-queues/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MyStack {
//push O(n)
public MyStack() {
}
Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
public void push(int x){
if(q1.isEmpty()) q1.offer(x);
while(!q2.isEmpty()) q1.offer(q2.poll());
while(!q1.isEmpty()) q2.offer(q1.poll());
}
public int pop(){return q2.poll();}
public int top(){return q2.peek();}
public boolean empty(){return q1.isEmpty() && q2.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();
*/

Complexity:

Time complexity:

push: O(n)

pop/top/empty: O(1)

Space complexity: O(n)

Welcome to my other publishing channels