I am confused about the last "return" statement in the Java implementation of linked list below.
here is the code:
//remove the node with duplicate data and return the linked list
static Node removeDuplicates(Node head) {
if(head == null)
return head;
Node temp = head;
while(null != temp.next) {
if(temp.data == temp.next.data)
temp.next = temp.next.next;
else
temp = temp.next;
}
return head;
}
The last "return" statement is "return head", but shouldn't it be "return temp"?? My explanation would be that temp node is created to copy the head node, and traverse the entire linked list. At the end of this operation, it is the temp that is modified if there is any duplicate data, so the last statement should be "return temp".
The code above that I am confused about is actually correct, can anyone explain it to me?
Thank you!