简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM