The following code works fine when head is sent as a parameter to it. As I am new to C, I couldn't understand how it works. Help me out please.
struct node *recursiveReverseLL(struct node *list)
{
struct node *revHead;
if (list == NULL || list->link == NULL)
{
return list;
}
revHead = recursiveReverseLL(list->link);
list->link->link = list;
list->link = NULL;
return revHead;
}
I dont know how the links are provided using those recursive calls. ie) if the links are as,
1 -> 2 -> 3 -> 4
then hw is it changed as,
4 -> 3 -> 2 -> 1
Reverse linked list is a linked list created to form a linked list by reversing the links of the list. The head node of the linked list will be the last node of the linked list and the last one will be the head node.
The general recursive algorithm for this is:
Divide
the list in 2
parts - first
node and rest of the list.rest
of the
linked list.rest
to first
.head
pointerHere is the code with inline comments:
struct node* recursiveReverseLL(struct node* first){
if(first == NULL) return NULL; // list does not exist.
if(first->link == NULL) return first; // list with only one node.
struct node* rest = recursiveReverseLL(first->link); // recursive call on rest.
first->link->link = first; // make first; link to the last node in the reversed rest.
first->link = NULL; // since first is the new last, make its link NULL.
return rest; // rest now points to the head of the reversed list.
}
I hope this picture will make things clearer:
(source: geeksforgeeks.org)
.
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