[英]reversing link list using recursion.why not head gets initialized with last node of the reversed list after completion of recursion?
这段代码工作正常但我不明白为什么head在程序完成后是新列表的第一个节点。
void reverse(struct node* h)
{
if(h->next==NULL)
{
head=h;
return;
}
reverse(h->next);
struct node* q=h->next;
q->next=h;
h->next=NULL;
}
诀窍在于递归退出步骤:
if(h->next==NULL)
{
head=h;
return;
}
该代码允许函数从递归中逃脱:
reverse(h->next);
它的作用是将原始列表的最后一个元素指定为头部元素,你需要理解if分支只会在递归的最后一步执行,这就是为什么head被分配了第一个节点的新名单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.