题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
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(new Integer(node));
}
public int pop() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());//把栈1的内容倒入栈2
}
}
return stack2.pop().intValue();
}
}
本文介绍了一种使用两个栈来实现队列的方法。通过这种方式,可以有效地完成队列的入队(Push)和出队(Pop)操作。当进行出队操作时,如果辅助栈为空,则将主栈的所有元素依次弹出并压入辅助栈中,再从辅助栈中弹出顶部元素即实现了队列出队。
304

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



