I was trying to read a program of removing duplicate elements in a linked list. I am confused about the break conditions put in the while loop. Below is the code.
public static <T> void removeDuplicates(SinglyLinkedList<T> list) {
SinglyLinkedList<T>.Node current = list.headNode; // will be used for outer loop
SinglyLinkedList<T>.Node compare = null; // will be used for inner loop
while ( current != null && current.nextNode != null) {
compare = current;
while (compare.nextNode != null) {
if (current.data.equals(compare.nextNode.data)) { //check if duplicate
compare.nextNode = compare.nextNode.nextNode;
} else {
compare = compare.nextNode;
}
}
current = current.nextNode;
}
}
The statement while ( current != null && current.nextNode != null)
is confusing to me. If I remove current != null
from the statement the output is produced same. Suppose the list is 1 -> 2 -> 3 -> null. Now initially current is at 1 , then if we traverse the list and when current points to 3 , at that moment (current.nextNode == null) and if I use only while( current.nextNode != null
, that does the job for me. Then why the author has used current != null
. Please help me clear the confusion.
CodePudding user response:
A completely empty list would have current
be null
. The dot is the dereference operator - dereferencing null
causes a NullPointerException. Hence, calling that method with an empty list would cause an NPE whereas the correct action is to do nothing ('remove all duplicates from this empty list' is a job that can be done, and it is done by doing nothing - there are no duplicates in an empty list, thus, nothing to remove).
For a non-empty list, indeed, that part of the while
clause is never going to be relevant. Given that it would never get there (the last node in the list would already fail the while clause due to having a current.nextNode
of null
).