始终保证有一个队列是空的!
class MyStack {
// Push element x onto stack.
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
public void push(int x) {
if (q1.isEmpty()) {
q2.add(x);
}
else{
q1.add(x);
}
}
// Removes the element on top of the stack.
public void pop() {
if (q2.isEmpty()) {
while (q1.size() != 1) {
q2.add(q1.poll());
}
q1.poll();
}
else{
while (q2.size() != 1) {
q1.add(q2.poll());
}
q2.poll();
}
}
// Get the top element.
public int top() {
int tmp;
if (q2.isEmpty()) {
while (q1.size() != 1) {
q2.add(q1.poll());
}
tmp = q1.peek();
q2.add(q1.poll());
}
else{
while (q2.size() != 1) {
q1.add(q2.poll());
}
tmp = q2.peek();
q1.add(q2.poll());
}
return tmp;
}
// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}