Search code examples
javanullpointerexception

Null Check when interating LinkedList throws NullPointerException


So I'm coding in Java, and I had to make a LinkedList manually. It is doubly linked, and the tail's next pointer points to null. I'm using this to iterate through the list until I reach the end for a sorting algorithm (bubble sort).

Node<?> current = a.getHead();
while (current.getNext() != null) { //this line throw a NullPointerException
         //sorting algorithm
        current = current.getNext();
}

Here's the code for getNext() as well: Node<?> current = a.getHead();. Why is Java throwing a NullPointerException here?


Solution

  • Problem is in line Node<?> current = a.getHead();

    a.getHead(); is returning null.
    

    Please check like -

    while (current != null && current.getNext() != null) {
             //sorting algorithm
            current = current.getNext();
    }