用随机指针c ++克隆链表

时间:2016-09-27 00:56:13

标签: c++ linked-list

我正在研究克隆具有随机指针的链表的问题。 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];
}

我从网上采纳了这个想法并试图实现它。但是我在第二行while循环中遇到了分段错误。任何暗示我的错误都会对我有所帮助。

1 个答案:

答案 0 :(得分:0)

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;

我修改过的代码正在运行。 谢谢@Jerry Coffin