Java双栈实现栈排序时临时栈为空引发空栈异常的修复方法
EmptyStackException 修复方案
异常触发根因
空栈异常的触发点位于else if (temp1 < stack2.peek())分支的内层元素迁移循环中:
- 原有循环条件仅判断
temp1 < stack2.peek(),未对stack2本身的空状态做前置校验 - 举个实际触发异常的场景:假设stack2内存储元素为[5,7](栈底到栈顶顺序),待插入的temp1为2。原有循环会依次弹出7、5移回stack1,当stack2完全清空后,循环仍会尝试读取空栈的栈顶值,直接抛出EmptyStackException。
核心修复逻辑
调整内层迁移循环的判断条件,利用Java的&&短路特性,先校验栈非空,再读取栈顶值做比较:
- 循环执行需同时满足两个条件:stack2不为空、stack2栈顶值大于当前temp1
- 一旦stack2被完全清空,循环立即终止,不会尝试读取空栈的栈顶值,从根源上避免异常触发
优化细节
- 将统计迁移元素数量的
count变量移入else if分支块内声明,避免方法级变量的残留状态带来的逻辑隐患
修复后完整可运行代码
import java.util.*; public class SortedStack { public static void sortStack(Stack<Integer> stack1) { Stack<Integer> stack2 = new Stack<Integer>(); while (!stack1.isEmpty()) { int temp1 = stack1.pop(); // 栈2为空时直接压入元素 if (stack2.isEmpty()) { stack2.push(temp1); } // 待插入值小于栈2栈顶值时,调整栈内元素位置 else if (temp1 < stack2.peek()) { int count = 0; // 修复点:先判断栈非空,再比较栈顶值,避免空栈调用peek while (!stack2.isEmpty() && stack2.peek() > temp1) { int temp2 = stack2.pop(); stack1.push(temp2); count++; } stack2.push(temp1); // 把之前移回栈1的元素重新压回栈2 while (count > 0) { int temp3 = stack1.pop(); stack2.push(temp3); count--; } } // 待插入值大于等于栈2栈顶值时,直接压入栈2 else { stack2.push(temp1); } } System.out.println(stack2.toString()); } public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack.add(34); stack.add(3); stack.add(31); stack.add(98); stack.add(92); stack.add(23); sortStack(stack); } }
内容的提问来源于stack exchange,提问作者SomeoneLearning17
相关产品推荐
相关产品推荐

