I've been playing around with recursion a little bit, admittedly it's been some time since I've used it, and I'm feeling pretty rusty. I was simply trying to recursively reverse a linked list and wasn't getting anywhere and finally google'd some code and came across the below snippet,
node * reverse(node *head) {
node *temp;
if (!head->next) temp = head;
else {
temp = reverse(head->next);
head->next->next = head;
head->next = NULL;
}
return temp;
}
The terminating condition is pretty obvious, but after the recursive call is where the confusion comes in. I'll walk through this, and if anybody would be so kind, could you please explain the section where confusion lies?
So, as each stack frame is pushed we're advancing down the list until our next pointer is null (i.e. we're at the last node). Let's say my list is the following,
[1]->[2]->[3]->[4]->[5]->NULL;
So when we start the stack unwinding when our if() conditional is true the following should hold.
- head points to node [5]
- temp is assigned head
- we return temp on line 9
Now we make our way to line 6 and here is where the confusion starts. The current stack frame has head pointing to node [5], head's next = NULL, so what does line 6 do? Specifically,
head->next->next = head;
After this is executed we know head->next->next is pointing back to itself. This confuses the hell out of me. Then moving on, why is line 7 setting head's next to NULL?
These last two steps seem to set up the chaining, but I'm lost as to what's going on.