在链表末尾添加节点

3

在向链表末尾添加节点时遇到了问题。 addToEnd 方法将一个单独的节点添加到链表末尾,代码非常简单易懂。

public class ll5 {
    // Private inner class Node

    private class Node{
        int data;
        Node link;

        public Node(int x, Node p){
            data = x;
            link = p;
        }
    }
    // End of Node class

    public Node head;

    public ll5(){
        head = null;
    }

    public void addToEnd(int data) {
        Node p = head;
        while (p.link != null)
            p=p.link;
        p.link=new Node(data, null);
    }


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ll5 list = new ll5();

        list.printList();
        System.out.println("How many values do you want to add to the list");
        int toAdd = input.nextInt();

        for(int i = 0; i < toAdd; i++) {
            System.out.println("Enter value " + (i + 1));
            list.addToEnd(input.nextInt());
        }

        System.out.println("The list is:");
        list.printList();

        input.close();
    }

}

为什么会出现 NullPointerException 错误?错误在 addToEnd 方法中的 while 循环中。

我猜 Node p = head 会使得 p = null,因为在第一次调用 addToEnd 时,headnull - StepTNT
2个回答

2

当列表为空且头部为null时,您没有处理初始条件。因此,您会收到NPE错误。

以下方法应该有效。

public void addToEnd(int data) {
    Node p = head;
    if( p == null) {
        head = new Node(data, null);
    } else {
        while (p.link != null)
            p=p.link;
        p.link=new Node(data, null);
    }
}

0

这是因为一开始头部是空的

public ll5(){
    head = null; // <-- head is null
}

public void addToEnd(int data) {
    Node p = head;  //<-- you assigned head, which is null, to p
    while (p.link != null) //<-- p is null, p.link causes NullException
        p=p.link;
    p.link=new Node(data, null);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接