初始化节点错误

时间:2018-07-14 22:22:15

标签: java nodes

我是Java新手。当我尝试初始化Node时,出现错误。 这是我的代码:

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

public class RemoveDups {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Node head=new Node(0);
        Node node=head.next;
        for(int i=0;i<20;i++) {
            node=new Node(i);
            node=node.next;         
        }
        node=head;
        while(node!=null){
            System.out.print(node.data);
            node=node.next;
        }
    }}

我收到NullPointerException。

Exception in thread "main" java.lang.NullPointerException

有人可以帮我吗!

1 个答案:

答案 0 :(得分:1)

您的node.next引用都没有初始化,因此它们都为空。

Node head = new Node(0);
Node node = head.next;  // this is null
for (int i = 0; i < 20; i++) {
    node = new Node(i);
    node = node.next;   // this is null
}
// none of the above nodes have been assigned a value for "next".

node = head;
while (node != null) {
    System.out.print(node.data); // contains node.data = 0 from head
    node = node.next;  // this is null since it was never assigned
                       // a value, so loop exits on next inspection
                       // of "node != null".
}

这是您想要尝试的解决方案:

Node.java:

public class Node {

    int data;

    Node next;

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

RemoveDups.java:

public class RemoveDups {

    public static void main(String[] args) {

        Node head = new Node(0);
        Node node = head;
        for (int i = 1; i <= 20; i++) {
            node.next = new Node(i);
            node = node.next;
        }

        node = head;
        while (node != null) {
            System.out.printf("Current node value is: %d\n", node.data);
            node = node.next;
        }
    }
}

输出:

Current node value is: 0
Current node value is: 1
Current node value is: 2
Current node value is: 3
Current node value is: 4
Current node value is: 5
Current node value is: 6
Current node value is: 7
Current node value is: 8
Current node value is: 9
Current node value is: 10
Current node value is: 11
Current node value is: 12
Current node value is: 13
Current node value is: 14
Current node value is: 15
Current node value is: 16
Current node value is: 17
Current node value is: 18
Current node value is: 19
Current node value is: 20