为什么temp.data == temp.next.data给出错误?



我正在做一个的问题,从LinkedList中消除重复项。我先在if语句中写了这段代码,我写了if(curr.data == curr.next.data),但它显示错误,在一个测试用例中,它显示运行时错误。两者不是一样的吗?使用(current .data.equals(current .next.data))有什么不同?

public static LinkedListNode<Integer> removeDuplicates(LinkedListNode<Integer> head) {
//Your code goes here
if (head == null)
return null;
LinkedListNode<Integer> curr = head;
while(curr.next != null)
{
if(curr.data == curr.next.data)
{
curr.next = curr.next.next;
}
else
{
curr = curr.next;
}
}
return head;
}

变化

while(curr.next != null)

while(curr != null)

在你的if块中,你正在检查curr.next = curr.next.next,但如果curr.next.next本身是null,如果它是null,那么你在while中的条件将导致错误。

最新更新