0

Hi there, I was trying to create a new linked list however failed to insert numbers in for some reason, I checked everything and still couldn't figure out, can someone help? thanks.

Node.java

public class Node {
public int data;
public Node next;
public Node(int data, Node next){;
this.data = data;
this.next = next;
}
public String toString(){
    return data + "";
}



public static Node addBeforeLast(Node infront, int item){
Node last = infront;
Node befLast = last;
while (last.next!=null)
{
    befLast = last;
    last = last.next;
}
Node tmp = new Node (item, last);
if (befLast == null)
{
    return tmp;
}
befLast.next = tmp;
return infront;
}
}

Test.java

 import java.util.Arrays;

public class Test
{
public static void main (String[] args)
{
    int[] array = new int[10];
    for (int i = 0; i < array.length; i++)
    {
        array[i] = i;
    }
    System.out.println(Arrays.toString(array));

    //Create a new linked list
    Node Ary = new Node(0, null);
    Node tmp = Ary;
    for (int j = 0; j < array.length; j++)
    {
        tmp.data = array[j];
        tmp = tmp.next;
    }

    //Test: print them out
    System.out.println(Ary);

}


}

Console:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:19)

0 Answers0