mardi 30 juillet 2019

Pointer variable is not being assigned

I'm trying to write a program to reverse a linked-list using recursion.The recursive function is working properly except in terminal condition the pointer variable(*start) that is being assigned a value is not reflecting in it after the function completes.

I put some print statements and found that in function the value is being assigned to pointer correctly.

 void revList(node *hd,node *start){
     if(hd->next==NULL){
         cout<<start<<endl; 
         start=hd;
         cout<<start<<endl; //this show it is being modified
         return;
     }
     node *first=hd;
     node *rest=hd->next;
     first->next=NULL;
     revList(rest,start);
     cout<<first<<" "<<rest<<endl;
     rest->next=first;
 }

int main(){ 
    node *head=new node;
    head->val=9;
    head->next=NULL;
    addnode(head,6);
    addnode(head,7);
    addnode(head,8);
    node *s;
    revList(head,s);
    cout<<s<<endl; //but it's not reflecting here.

    while(s!=NULL){
        cout<<s->val<<"->";
        s=s->next;
    }
return 0;
}

//output:
0x7ffd5c1422c0                                                                                                           
0x1e45c80                                                                                                                
0x1e45c60 0x1e45c80                                                                                                      
0x1e45c40 0x1e45c60                                                                                                      
0x1e45c20 0x1e45c40                                                                                                      
0x7ffd5c1422c0                                                                                                           
Segmentation fault (core dumped)//I'm not worried about this.

Aucun commentaire:

Enregistrer un commentaire