数组实现的MyStack迁移栈元素触发StackEmptyException问题求助
异常原因排查
1. 核心错误:MyStack的pop()方法判断逻辑写反
你当前pop()方法的空栈判断条件完全错误:
// 错误写法 public int pop() { // 移除并返回栈顶元素 if(top<array.length) { System.out.println("StackEmptyException"); } int x = array[top--]; return x; }
- 空栈的正确判断条件应该是
top < 0,你写的top < array.length在任何正常使用栈的场景下都会成立(top最大取值为array.length-1),只要调用pop方法,不管栈有没有元素,都会触发空栈提示 - 当栈真的为空(
top=-1)时,你没有终止方法执行,会继续访问array[-1],直接触发数组越界异常,这就是你运行时报错的直接原因
2. 附带问题1:push()方法栈满判断逻辑不完整
你当前push()方法判断栈满后,只是打印异常提示,没有终止方法执行,仍然会执行array[++top] = x,栈满时会触发数组越界:
// 错误写法 public void push(int x) { // 向栈顶压入元素 if(top>=array.length-1) { System.out.println("StackFullException"); } array[++top] = x; }
3. 附带问题2:dequeue()方法逻辑不完整
你当前把stack1的元素全部倒入stack2后,直接返回初始化的x=0,没有取出stack2的栈顶元素作为出队结果,不符合双栈模拟队列的逻辑。
修复后代码示例
修复后的MyStack类
public class MyStack { static final int MAX = 100; private int[] array = new int[MAX]; private int top; public MyStack(){ top = -1; } boolean isEmpty() { return (top < 0); } public void setArraySize(int x) { array = new int[x]; top = -1; // 调整数组大小后重置栈顶指针,避免逻辑错误 } public int peek(){ // 返回栈顶元素 if(isEmpty()) { throw new RuntimeException("StackEmptyException"); } return array[top]; } public void push(int x) { // 向栈顶压入元素 if(top>=array.length-1) { throw new RuntimeException("StackFullException"); } array[++top] = x; } public int pop() { // 移除并返回栈顶元素 if(isEmpty()) { throw new RuntimeException("StackEmptyException"); } int x = array[top--]; return x; } }
修复后的dequeue方法
public int dequeue() { if(stack1.isEmpty()) { throw new RuntimeException("QueueEmptyException"); } // 将stack1元素全部迁移到stack2 while(!stack1.isEmpty()) { stack2.push(stack1.pop()); } // stack2栈顶即为队首元素 int res = stack2.pop(); // 剩余元素迁回stack1等待后续操作 while(!stack2.isEmpty()) { stack1.push(stack2.pop()); } return res; }
内容的提问来源于stack exchange,提问作者Stephen Enrile
相关产品推荐
相关产品推荐

