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
Restis initialised to the tail node, which after that call returns is assigned to the pass-by-referenceheadvariable. Thisheadreference is theRestvariable of the caller, so also that caller's localRestnow points to the tail. And so the unwinding continues where eachhead = Restcopies that tail reference to the caller'sRestvariable (becauseheadis a pass-by-reference parameter).That
head = Restassignment really is like the "portal" back to the caller. And so each caller gets their ownRestvariable to point to the original tail node, which is now the head of the reversed list.