void reverseLinkedList(Node* &head)
{
if (head == nullptr || head->next == nullptr)
{
return ;
}
Node* Rest = head->next;
reverseLinkedList(Rest);
head->next->next = head;
head->next = nullptr;
head = Rest;
}
int main()
{
Node* h = nullptr;
Create(h, 4);//create linked-list with N nodes
reverseLinkedList(h);
Print(h);
}
according to the debugging, the Rest variable still has the same value during the stack unwinding. does it is supposed to be changed every call stack? but it still has the same value in each call.
This is expected.
When the last recursive call occurs, the local variable
Rest
is initialised to the tail node, which after that call returns is assigned to the pass-by-referencehead
variable. Thishead
reference is theRest
variable of the caller, so also that caller's localRest
now points to the tail. And so the unwinding continues where eachhead = Rest
copies that tail reference to the caller'sRest
variable (becausehead
is a pass-by-reference parameter).That
head = Rest
assignment really is like the "portal" back to the caller. And so each caller gets their ownRest
variable to point to the original tail node, which is now the head of the reversed list.