链表空指针异常



我不确定这里出了什么问题,我在网上看过,我看到人们实现删除链表的方式略有不同,但我不确定出了什么错误,也不确定为什么我会得到一个空指针异常

class GfG
{
Node deleteNode(Node head, int x)
{
// Your code here   
//checks the first nodes value, if found, changes head to equal next node
Node current = head;
if(head.data == x){
head = head.next;
return head;
}

while(current != null){
//if statement checks for next nodes data value for comparions
if(current.next.data == x){
current.next = current.next.next;
return head;
}
current = current.next;
}
return head;
}
}

注意:不要发布代码的图片。按原样张贴您的代码。

您不会在while循环中检查是否有下一个元素。

如果您位于列表的末尾,则current.next == nullcurrent.next.data会触发一个空指针异常。

最新更新