class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
private Integer top;
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList();
queue2 = new LinkedList();
}
/** Push element x onto stack. */
public void push(int x) {
queue1.add(x);
top = x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while (queue1.size() != 1) {
top = queue1.remove();
queue2.add(top);
}
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = new LinkedList<>();
return temp.remove();
}
/** Get the top element. */
public int top() {
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}
注:
用两个队列,每次要pop的时候就把第一个传给第二个,直到剩一个。循环往复。