比较简单,第一个栈用于作入队,另一个队列用于出队,当需要出队时把第一个队列元素全部倒入第二个队列,这样从第二个队列出来的便是第一个进去的元素。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (!stack2.isEmpty()) {
return stack2.pop();
}
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
if (!stack2.isEmpty()) {
return stack2.pop();
}
return -1;
// throws new IllegalArgumentException("队列空");
}
}