Search code examples
clistrecursionhyperlinkdestroy

Removing Elements From a Linked List Recursively in C


I am currently studying for a test by doing practice problems the teacher posted for us to study off of and I am struggling with the deleting elements from a linked list recursively. I get an endless loop and I'm not quite sure why! Can someone please tip me into the right direction? I have made a method that deletes the elements without recursion (posted below) and tried to follow that was a guideline. However, I just cannot seem to get my recursion method to work. Below is my code:

void destroyListRecursive(node *head)
{
    if ( head == NULL)
        return;

    destroyListRecursive(head->next);

    free(head);
}

Here is my none recursive function (which I looked at other articles to receive guidance on since I was having a few issues, please let me know if there is something wrong with it) :

void destroyList (struct node** head)
{
   struct node* current = *head;
   struct node* next;

   while (current != NULL) 
   {
       next = current->next;
       free(current);
       current = next;
   }

   *head = NULL;
}

Here is my list struct:

typedef struct node
{
    // data field
    int data;

    // the next node in the list
    struct node *next;
} node;

I'd really appreciate a nudge in the correct direction! :)


Solution

  • Your code dereference a NULL pointer on last element of your linked list with

    if ( head->next == NULL)
        return;
    

    When last element is passed recursively to the function its value will be in head parameter, so

    if ( (NULL)->next == NULL)
        return;
    

    That is Undefined Behavior

    Your recursive function must only check head value:

    void destroyListRecursive(node *head)
    {
        if ( head == NULL)
            return;
    
        destroyListRecursive(head->next);
    
        free(head);
    }