Null Check when interating LinkedList throws NullPointerException

GildedTruth :

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?

Dipankar Baghel :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238206&siteId=1