Recursive Solution not working


#1

Why is recursive solution giving runtime :stack overflow error?

public static List deleteDuplicates(ListNode A) {
if(A==null||A.next==null)
{
return A;
}

        ListNode nh=deleteDuplicates(A.next);
        if(A.data.equals(nh.data))
        {
        	A.next=nh.next;   
        }
        return A;
        
    }

#2

Please See to your approach:
Lemme give it to you:

  1. Check if the given node is NULL if yes, return NULL;
  2. Now for recursion, you need three things:
    a. BASE CASE: this you checked.
    b. Do your work: Your work here includes traversing the linked list till you are finding the consecutive duplicates, for eg: 1->1->1->1->2->3->4-> 4, here you need to traverse till the last one and make it the new head.
    c. Call recursion, just check for the corner case if you are never taking next of NULL pointer, it will result in a segmentation fault.

Hope it helps!


#3

you should return A, only when A.data != nh.data, else return nh.
if(A.data == nh.data) return nh ;
else
{
A.next = nh ;
return A ;
}