题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
- push 动作都在 stack1 中进行,pop 动作在 stack2 中进行。
- 边界条件判断,栈为空时,抛出异常。
- 当 stack2 不为空时,直接 pop;
- 当 stack2 为空时,先把 stack1 中的元素 pop 出来,push 到 stack2 中,再从 stack2 中 pop 元素。
代码:
package 用两个栈实现队列07;
import java.util.Queue;
import java.util.Stack;
/**
* 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
*/
public class Demo {
// 压入栈
Stack<Integer> stack1 = new Stack<Integer>();
// 弹出栈
Stack<Integer> stack2 = new Stack<Integer>();
// 压栈,在队列尾部插入节点
public void push(int node) {
stack1.push(node);
}
// 弹栈,将队列头部节点弹出
public int pop() {
if (stack1.isEmpty() && stack2.isEmpty()) { // 若【弹出栈】和【压入栈】均为空
throw new RuntimeException("队列为空"); // 抛出异常提示队列为空
}
int node; // 创建一个节点,用于接收【弹出栈】的元素
if (stack2.isEmpty()) { // 当【弹出栈】为空时,把【压入栈】的元素 pop 出来,push 到【弹出栈】,再从【弹出栈】弹出
while (!stack1.isEmpty()) {
node = stack1.pop();
stack2.push(node);
}
}
return stack2.pop();
}
}