簡體   English   中英

使用隨機指針克隆鏈接列表C ++

[英]Clone a linked list with random pointer c++

我正在研究克隆具有隨機指針的鏈表的問題。 問題陳述

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循環的第二行遇到了分段錯誤。 任何提示我的錯誤都會對我有所幫助。

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;

我修改后的代碼有效。 謝謝@傑里·科芬

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM