I need to return the head of the linked list with all the duplicate elements deleted. I understand the logic of the problem, but I am getting confused in using recursion.
/*
Node is defined as
class Node {
int data;
Node next;
}
*/
Node RemoveDuplicates(Node head) {
if ((head == null) || (head.next == null))
return head;
else {
RemoveDuplicates(head.next);
if (head.data==head.next.data) head.next = head.next.next;
}
return head;
}
If I call the function RemoveDuplicates(head.next) before the if condition; it works fine. However if I swap the order of the statements (rest everything is exactly the same)like:
if (head.data==head.next.data) head.next = head.next.next;
RemoveDuplicates(head.next);
the code is unable to correctly solve for a test case like '1->1->1->1'. The output I get in the latter case is '1->1'.
I would really like some suggestions on how I could understand recursion better.
==precedes||)[docs.oracle.com/javase/tutorial/java/nutsandbolts/…. - By convention, methods in Java are not capitalized, i.e. it should be namedremoveDuplicatesin this case.