Implement Stack by Two Queues
push(1)
pop()
push(2)
isEmpty() // return false
top() // return 2
pop()
isEmpty() // return true push(1)
pop()
push(2)
isEmpty() // return false
top() // return 2
pop()
isEmpty() // return true class Stack {
Deque<Integer> q1;
Deque<Integer> q2;
public Stack() {
this.q1 = new LinkedList<>();
this.q2 = new LinkedList<>();
}
// Push a new item into the stack
public void push(int x) {
q2.addFirst(x);
while (! q1.isEmpty()) {
q2.addFirst(q1.removeLast());
}
Deque<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
// Pop the top of the stack
public void pop() {
q1.removeLast();
}
// Return the top of the stack
public int top() {
return q1.peekLast();
}
// Check the stack is empty or not.
public boolean isEmpty() {
return q1.isEmpty();
}
}