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.
the Rest variable still has the same value during the stack unwinding.
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-reference head
variable. This head
reference is the Rest
variable of the caller, so also that caller's local Rest
now points to the tail. And so the unwinding continues where each head = Rest
copies that tail reference to the caller's Rest
variable (because head
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 own Rest
variable to point to the original tail node, which is now the head of the reversed list.