简体   繁体   中英

reversing link list using recursion.why not head gets initialized with last node of the reversed list after completion of recursion?

This code works fine but i don't understand why head is first node of new list after the completion of the program.

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;   
}

The trick is in the recursion exit step:

if(h->next==NULL)         
{ 
   head=h;
   return;
}

That code, allows the function to escape from the recursion:

reverse(h->next);

What it does is to assign the last element of the original list as the head one, you need to understand that the if branch is only going to be executed on the last step of the recursion, thats why head gets assigned the first node of the new list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM