Use two queues to implement stack.
q2 is used to make sure the new element is always at the front of the q1.
public class Solution {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
//pop: dequeue in q1
public void pop() {
if (q1.peek() == null) {
System.out.println("The stack is empty!");
} else {
int pop = q1.remove();
return pop;
}
}
//1.dequeue all the items from q1 to q2
//2.enqueue the new item in q1
//3.dequeue all the items in q2 to q1
public void push(int data) {
if (q1.peek() == null) {
q1.add(data);
} else {
for (int i = q1.size(); i > 0; i--) {
q2.add(q1.remove());
}
q1.add(data);
for (int j = q2.size(); j > 0; j--) {
q1.add(q2.remove());
}
}
}
}