一个栈A用来保存入队列的数据,另一个栈B用来出队。如果栈B是空的,就需要把栈A全部弹出压入栈B,然后弹出一个元素即可。如果栈B不为空,直接弹出一个元素即可。
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.size()>0) return stack2.pop();
while(stack1.size()>0){
stack2.push(stack1.pop());
}
return stack2.pop();
}
京公网安备 11010502036488号