[英]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.