我是新来的,我有一个问题。 我试图通过top来实现比较器来比较两个堆栈。 代码看起来像这样
class Comp implements Comparator<Stack<Integer>> {
@Override
public int compare(Stack<Integer> st1,Stack <Integer> st2) {
return st1.peek()-st2.peek();
}
}
我在java.util.EmptyStackException
得到了st1.peek()-st2.peek();
而且我不知道为什么。也许你会帮助我更好地实现我的问题。谢谢!
答案 0 :(得分:1)
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();
}