Hi, I am trying to reverse a linked list recursively. But the problem is that I am not able to understand the code.
Here's the code:
Code:
void recursiveReverse(struct node** head_ref)
{
struct node* first;
struct node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->link;
/* List has only one node */
if (rest == NULL)
return;
/* put the first element on the end of the list */
recursiveReverse(&rest);
first->link->link = first;
/* tricky step -- see the diagram */
first->link = NULL;
/* fix the head pointer */
*head_ref = rest;
}
Let the input linked list be 1->2->3->4
Here, I am not getting how the head_ref variable points to 4 at the end of the program. What I get is that head_ref should point to 2 instead of 4 as it is equal to rest.
Maybe I am facing this problem because my recursion concepts are not clear. Any help will be appreciable.