简体   繁体   中英

Clone a linked list with random pointer c++

I am working on the problem of cloning a linked list that has a random pointer. Problem Statement

LinkListNode* CloneLink(LinkListNode* orig){
    LinkListNode* cloneLinkStart=NULL;
    LinkListNode* head=orig;
    map<LinkListNode*,LinkListNode*> m;
    while(head){
        cloneLinkStart=new LinkListNode(head->val);
        m[cloneLinkStart]=head;
        head=head->next;
   }
   head=orig;
   while(head){
       cloneLinkStart=m[head];
       cloneLinkStart->next=m[head->next];
       cloneLinkStart->random=m[head->random];
       head=head->next;
   }
   return m[orig];
}

I have taken the idea from online and tried to implement it. But I am getting a segmentation fault in the second line of second while loop. Any hints to my mistake will help me.

if(!head)
        return head;
    RandomListNode* cloneLinkStart=NULL;
    RandomListNode* orig=head;
    map<RandomListNode*,RandomListNode*> m;
    while(orig){
        cloneLinkStart=new RandomListNode(orig->label);
        m[orig]=cloneLinkStart;
        orig=orig->next;
   }
   orig=head;
   while(orig){
       cloneLinkStart=m.find(orig)->second;
       if(orig->next)
            cloneLinkStart->next=m.find(orig->next)->second;
       else
            cloneLinkStart->next=NULL;
        if(orig->random)
            cloneLinkStart->random=m.find(orig->random)->second;
        else
            cloneLinkStart->random=NULL;
        orig=orig->next;
        cloneLinkStart=cloneLinkStart->next;
   }
   return m.find(head)->second;

My modified code that's working. Thanks @Jerry Coffin

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