Reputation: 300
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.
Upvotes: 1
Views: 2701
Reputation: 8255
The first example terminates when temp == null
, meaning that temp
will 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 == null
but 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.
Upvotes: 2
Reputation: 1
The second loop will generate a nullPointerException while executing the condition so it is not an efficient way.
Upvotes: 0
Reputation: 9340
The second has a potential of getting NullPointerException if temp itself is null when checking the while condition for the first time. The first is safe from such exception.
The second would end up in the last element in the linked list, while the first would end up in null.
Upvotes: 0
Reputation: 5264
the first will stop one link later than the second one so if you want to process every node then use the first.
Upvotes: 1