用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
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.empty()){
return stack2.pop();
} else{
while(!stack1.empty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}

本文介绍了一种使用两个栈来实现队列的方法。通过这种方式,可以有效地完成队列的入队(push)和出队(pop)操作。队列中的元素类型为整型。具体实现包括:当执行push操作时,直接将元素压入第一个栈;执行pop操作时,如果第二个栈为空,则将第一个栈的所有元素依次弹出并压入第二个栈,再从第二个栈中弹出顶部元素。
2291

被折叠的 条评论
为什么被折叠?



