当我尝试创建新的链接列表时发生错误

时间:2016-04-09 17:03:14

标签: java linked-list

  

您好,我正在尝试创建一个新的链接列表,但由于某些原因未能插入数字,我检查了所有内容但仍然无法弄清楚,有人可以帮忙吗?感谢。

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

}


}

控制台:

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

0 个答案:

没有答案