import java.util.Stack;
/**
* 在进行栈弹出、查看栈顶元素等操作时,需要先判断栈是否为空。
*/
public class EmptyStackExcep {
public static void main(String[] args) {
Stack<Integer> stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
1.这种会出错EmptyStackException,因为要先判断栈是否为空,
然后再进行继续判断。
* 输出:3 2 1
* 然后 报异常
* Exception in thread "main" java.util.EmptyStackException
while (stack.peek() >= 0 && stack.peek() <= 9) {
if (!stack.isEmpty())
System.out.println(stack.pop());
else
break;
}
* 2.这种正常,因为他先判断了栈是否为空,然后再进行后续操作
* 正常输出:3 2 1
while (!stack.isEmpty()){
if (stack.peek() >= 0 && stack.peek() <= 9)
System.out.println(stack.pop());
else
break;
}
}
}
LC1—栈操作时,考虑是否判断栈是否为空
最新推荐文章于 2021-08-08 15:07:43 发布