分析:
队列先进先出,栈后进先出。两个栈可以用来调整顺序实现进出队列。
在元素进队列时,首先看栈2还有没有元素。为什么会有栈2还有元素的情况?因为可能push调用了三次,比如1、2、3分别进队列而pop只调用了两次,比如1、2出来了。这样就剩了一个元素没出来,也就是3。下次再进元素时,一定要保证3先出去。所以进队列一定要把栈2的剩下的元素全都搞到栈1中来。
在元素出队列就很简单了,把栈1的元素放到栈2中,栈2再依次出栈就好啦。
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
if(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}