So I was practicing some linked list problems and I keep getting mixed up with let say we do
// this is a head only singly linked list
// what is the difference between
ListNode temp = head;
while( temp != null ) {
temp = temp.next ;
}
while( temp.next != null ) {
temp = temp.next ;
}
again what is the difference between the two ? If you can please explain to me this it would be greatly appreciated.
The first example terminates when
temp == null, meaning thattempwill have the value null after the loop and not be of much use to you, though for processing the items in the list this is a perfectly valid approach.The second example will stop when
temp.next == nullbut temp itself actually has a value, in this case it will be a reference to the tail of the list, which is far more useful if you want to add something else on to the list as well.As some others have indicated, the second will cause a null dereference exception if temp is null, but this would only be an issue if temp was null before processing the loop, so this can be averted with a conditional.