One minute
Leetcode 225
Implementing Stacks Using Queues
Head on over here to try the problem for yourself.
The solution talks about using 2 queues, which frankly I don’t understand :’). I used a single queue to implement this problem.
Algorithm
The goal is to implement a stack using the basic queue features provided such as push()
, peek()
and pop()
. The easiest way to implement this is by inserting elements in reverse order. Then the queue will pop the elements like a stack.
Code
public class MyStack {
Queue<Integer> q;
public MyStack() {
q = new LinkedList<>();
}
public void push(int x) {
q.add(x);
for(int i = 0; i < q.size() - 1; i++) {
q.add(q.remove());
}
}
public int pop() {
return q.remove();
}
public int top() {
return q.peek();
}
public boolean empty() {
return q.size() == 0;
}
}