Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Linked List Recursively

Tags:

c

linked-list

I have a Node defined in Linked List as:

typedef struct abc
{
    int id;
    struct abc *next;        
}node;

I want to reverse a Linked List recursively.I am passing the head pointer to the function. My function definition looks like:

node *reverseLinkedListRecursively(node *head)
{
    node *current;
    node *rest;
    if(head == NULL)
        return head;

    current=head;
    rest=head->next;

    if(rest == NULL)
    {
       return rest;
    }
    reverseLinkedListRecursively(rest);
    current->next->next=rest;
    current->next=NULL;
    return rest;
}

How should I proceed? I have implemented the iterative approach.

like image 691
aj983 Avatar asked Dec 01 '22 01:12

aj983


1 Answers

It should work as follows:

node *reverseLinkedListRecursively(node *rest, node *reversed)
{
    node *current;

    if (rest == NULL)
        return reversed;

    current = rest;
    rest = rest->next;
    current->next = reversed;

    return reverseLinkedListRecursively(rest, current);
}

Initially, start it with:

reverseLinkedListRecursively(linkedList, NULL);

BTW: This function is tail-recursive. So a state-of-the-art compiler should be able to turn this recursive solution into a more efficient iterative solution.

like image 66
Codo Avatar answered Dec 05 '22 01:12

Codo