-1

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

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;
        }
    }
4

1 回答 1

1

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

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

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

于 2021-03-23T17:19:15.683 回答