NullPointerException Error using linked lists

☆樱花仙子☆ 提交于 2019-12-02 12:24:46
Node head = null;

whenever you call a method on a null object you get an nullPointerException.That is why head.setNext(first); is giving you exception. so instead of this you can do

Node head = new Node();

you will avoid NullPointerException with this.

According to your requirement you should do this.

private static Node buildList() throws IOException
{
 // Post : Inserts 0 or more numerical values from keyboard into list
//          using the Scanner class and returns head of list

Scanner input = new Scanner(System.in);
Node head = null;
Node first = new Node(input.nextInt());
head=first; //assigning the first value to head
while(input.hasNext())
{    
insert(first, input.nextInt());
head.setNext(first);//insert the node in the list
}
return first;
} 

Note: I am assuming that setNext() inserts the node in the list at appropriate location not directly in the next position of head node (otherwise you will get only 2 nodes no matter how many numbers you insert)

Node head = null;

The above line will make the head which is an object reference variable of type Node to null, now calling any method on this object reference variable will lead to NullPointerException.

Node head = new Node();

The line will be a better approach as this will prevent the NullPointerException.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!