singly-linked list data structure in Java -


i confused last "return" statement in java implementation of linked list below.

here code:

//remove node duplicate data , return 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 "return head", shouldn't "return temp"?? explanation temp node created copy head node, , traverse entire linked list. @ end of operation, temp modified if there duplicate data, last statement should "return temp".

the code above confused correct, can explain me?

thank you!

a handle linked list head of list. code doesn't reverse list. removes duplicates. more precisely, if temp.data identical temp.next.data, temp.next being removed. head of list never changed in process, therefore correct return original head, since head of modified list.

for instance, suppose original list head --> --> b --> c, head,a,b,c denote nodes in list, , suppose the value of a identical values of b. remove duplicates, change "next" pointer in a point c instead of b. yields modified list head --> --> c. head node of list identical head node of original list, , why return head.


Comments