gpt4 book ai didi

java - 尝试实现 Comparator 时出现 EmptyStackException

转载 作者:行者123 更新时间:2023-11-30 07:02:57 26 4
gpt4 key购买 nike

我是新来的,我有一个问题。我正在尝试实现一个比较器来按顶部比较两个堆栈。代码如下所示

class Comp implements Comparator<Stack<Integer>> {
@Override
public int compare(Stack<Integer> st1,Stack <Integer> st2) {
return st1.peek()-st2.peek();
}
}

我在 st1.peek()-st2.peek(); 处遇到 java.util.EmptyStackException,但我不知道为什么。也许你会帮助我更好地解决我的问题。谢谢!

最佳答案

当堆栈为空时,

Stack.peek 抛出 EmptyStackException。在调用peek之前,您需要检查堆栈是否为空,例如,如果您希望空堆栈位于非空堆栈之前:

@Override
public int compare(Stack<Integer> st1, Stack<Integer> st2) {
if (st1.isEmpty() && st2.isEmpty()) {
return 0;
}
if (st1.isEmpty()) {
return -1;
}
if (st2.isEmpty()) {
return 1;
}
return st1.peek() - st2.peek();
}

或者,如果您希望空堆栈出现在非空堆栈之后:

@Override
public int compare(Stack<Integer> st1, Stack<Integer> st2) {
if (st1.isEmpty() && st2.isEmpty()) {
return 0;
}
if (st1.isEmpty()) {
return 1;
}
if (st2.isEmpty()) {
return -1;
}
return st1.peek() - st2.peek();
}

关于java - 尝试实现 Comparator 时出现 EmptyStackException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40574367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com