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
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)
.