Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将节点添加到链接列表的末尾_Java_Linked List - Fatal编程技术网

Java 将节点添加到链接列表的末尾

Java 将节点添加到链接列表的末尾,java,linked-list,Java,Linked List,在将节点添加到链接节点的末尾时遇到问题 代码非常简单,addToEnd方法在linkedlist的末尾添加了一个节点 public class ll5 { // Private inner class Node private class Node{ int data; Node link; public Node(int x, Node p){ data = x; link =

在将节点添加到链接节点的末尾时遇到问题 代码非常简单,addToEnd方法在linkedlist的末尾添加了一个节点

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();
    }

}
公共类ll5{
//私有内部类节点
私有类节点{
int数据;
节点链接;
公共节点(int x,Node p){
数据=x;
link=p;
}
}
//节点类结束
公共节点头;
公共ll5(){
head=null;
}
公共void addToEnd(整型数据){
节点p=头部;
while(p.link!=null)
p=p.link;
p、 链接=新节点(数据,空);
}
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
ll5列表=新的ll5();
printList();
System.out.println(“您希望向列表中添加多少值”);
int toAdd=input.nextInt();
for(int i=0;i

为什么它会给我一个NullPointerException错误??错误在addToEnd方法的while循环中的某个地方

当list为空且head为空时,您尚未处理初始条件。正因为如此,你得到了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);
    }
}

那是因为开头的头是空的

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);
}
public ll5(){

head=null;//我猜
Node p=head
会使
p=null
生效,因为当您第一次调用
addToEnd
head
null