Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursively reverse a linked list in C

Given the struct ListNode:

typedef struct _listnode
{
    int item;
    struct _listnode *next;
} ListNode;

how to recursively reverse a linked list using a function with void return type and single parameter for passing in the address pointing the head ListNode of the linked list? (note that the function should not have a return type; the reversed linked list is accessible from the outside of the function so that the elements can be printed)

void reverseList(ListNode **headptr)
{
    if ((*headptr) == NULL)
        return;

    ListNode *first = *headptr;
    ListNode *rest = first->next;

    if (rest == NULL)
    {
        *headptr = first;
        return;
    }

    reverseList(&rest);

    rest->next = first;
    first->next = NULL;
}

Apparently the code above only returns the first element of the original list, without being reversed, while the remaining elements are gone.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem with your function implementation is that in this call

reverseList(&rest);

the function changes the local variable rest

ListNode *rest = first->next;

instead of changing the data member first->next.

So in this if statement

if (rest == NULL)
{
    *headptr = first;
    return;
}

the local variable declared in the previous recursive call of the function is changed. You need to pass to each recursive call of the function the pointer to the original head node through pointer to it.

And you function has too many return statements.

The function can look the following way:

void reverseList( ListNode **head )
{
    if (*head && ( *head )->next)
    {
        ListNode *last = *head;

        *head = ( *head )->next;

        reverseList( head );

        last->next->next = last;
        last->next = NULL;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading