LinkedList 空指针错误。当我尝试打印 LinkedList [duplicate] 中的元素时,我不断收到空指针异常

LinkedList null pointer error. I keep on getting a null pointer exception when trying to print the elements in the LinkedList [duplicate]

提问人:Amanda James 提问时间:11/3/2023 最后编辑:StackFlowedAmanda James 更新时间:11/3/2023 访问量:44

问:

尝试打印列表中的元素时,我不断收到空指针异常。异常命中了 print() 中我开始 while 循环的行。有没有办法解决这个问题?谢谢

class LinkedLists {

    private Node node;  

    public LinkedLists() {  
        
    }

    public void add(int d) {
        Node newNode = new Node(d);
        Node curr = node;
    
        if(curr == null) 
            curr = newNode;
    
    
        while(curr.next != null) {
            curr = curr.next;       
        }       
        curr.next = newNode;
    
        return;
    }

    public void print() {
    
        Node curr = node;
    
        while(curr.next != null) {
            System.out.println(curr.data);
            curr = curr.next;
        }
        System.out.println(curr.data);  
    }


    public static void main(String[] args) {
        LinkedLists list = new LinkedLists();
        list.add(3);
        list.add(12);
        list.add(99);
        list.add(6);
    
        list.print();       
    }

}

public class Node {

    Node next;
    int data;

    public Node(int d) {
        data = d;
        next = null;        
    }
}
Java 链接列表 NullPointerException

评论

1赞 user207421 11/3/2023
node如果列表为空,则为 null。您需要处理这种情况。
1赞 shmosel 11/3/2023
@user207421 实际上,它总是 null。

答:

-1赞 Awwal15 11/3/2023 #1

尝试这样做

public class Node 
{
  Node? next;
  int data;

  public Node(int d)
  {
     this.data = d;
     this.next = null;   
  }
}

不要担心这个关键词

1赞 StackFlowed 11/3/2023 #2

问题是你总是在开始时设置。

Node curr = node;

您需要在检查后执行此操作。

class LinkedLists {

    private Node headNode;  

    public LinkedLists() {  
        
    }

    public void add(int d) {
        Node newNode = new Node(d);
        //remove it from here 
        
        if(headNode == null) {
            headNode = newNode;
            return;
        }       
        //Added it here 
        curr = headNode;
        while(curr.next != null) {
            curr = curr.next;       
        }       
        curr.next = newNode;
    
        return;
    }

    public void print() {
    
        Node curr = headNode;
    
        while(curr.next != null) {
            System.out.println(curr.data);
            curr = curr.next;
        }
        System.out.println(curr.data);  
    }


    public static void main(String[] args) {
        LinkedLists list = new LinkedLists();
        list.add(3);
        list.add(12);
        list.add(99);
        list.add(6);
    
        list.print();       
    }

}

public class Node {

    Node next;
    int data;

    public Node(int d) {
        data = d;
        next = null;        
    }
}