剑指offer 9 用两个栈实现队列
代码:
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()){//很重要!!!
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}}
int ans=stack2.pop();
return ans;
}
} if(stack2.isEmpty)判断条件很重要,因为如果stack2不为空,那么直接从stack2弹出一个元素就好。如果它为空,才将从stack1弹出的先push进stack2,再pop
