I'm having trouble understanding how the algorithm for reversing the linked list fixes the head pointer.
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->next;
/* List has only one node */
if (rest == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;
}
I understood everything before that, its the last line that I don't get.
If the list is 1->2->3. So, recursiveReverse(2) will set *head_ref as 3. But when it returns to recursiveReverse(1), here rest points to 2. So shouldn't that set *head_ref to 2, (which is incorrect) but it doesn't actually. How does this work?
head_refis actually the parameter&restthat you pass in to the recursive call. I suggest that you run in a debugger, and step through the code line by line, and step into each recursive call. For a small list of three or four nodes it's pretty quick and should give you more insight.