题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 一个栈(如
stack1)只能用来存,另一个栈(如stack2)只能用来取 - 每次必须有一个栈为空,即所有元素必须同时在一个栈中
- 当加入元素时首先检查
stack2是否为空,如果不空将stack1中的元素全部倒入stack2,否则直接加入到栈1。加入之后再倒回是stack2
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(stack2.size()!=0){
stack1.push(stack2.pop());
}
stack1.push(node);
while(stack1.size()!=0){
stack2.push(stack1.pop());
}
}
public int pop() {
return stack2.pop();
}
}

本文介绍了一种使用两个栈实现队列的方法,通过巧妙地在两个栈之间转移元素,实现了队列的Push和Pop操作。文章详细解释了操作流程,并提供了Java代码实现。
2453

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



