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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With