I am trying to implement a LinkedList. The methods are functioning perfect on this example:
LinkedList list = new LinkedList();
Node newNode = new Node("sarah", 20);
list.addToBack(newNode);
System.out.println(list.nodeAt(0).getName());
But not on this example, when I try to use the same method with an array:
LinkedList[] list = new LinkedList[3];
Node newNode = new Node("sarah", 20);
list[1].addToBack(newNode);
System.out.println(list[1].nodeAt(0).getName());
For the last example I get the following:
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:27)
It's the line where addToBack method is called. This is the method:
public void addToBack(Node newNode) throws NullPointerException {
if (this.head == null){
this.head = newNode;
return;
}
Node current = this.head;
while (current.hasNext()){
current = current.next;
}
current.next = newNode;
++size;
}