栈1负责进栈,栈2负责出栈
用两个栈实现队列
http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6
入栈操作都往stack1入栈
出栈时,先判断stack2中是否有元素,如果没有,则stack1中元素全部出栈放入stack2中,然后从stack2中取栈顶元素;
如果stack2中有元素,则直接从stack2中出栈
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() && stack1.isEmpty()){
return Integer.MIN_VALUE;
}
if (!stack2.isEmpty()){
return stack2.pop();
}else {
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
查看11道真题和解析
