2016-09-27 56 views
0

我正在克隆具有隨機指針的鏈表的問題。 Problem Statement用隨機指針克隆鏈表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循環的第二行中遇到了分段錯誤。任何提示我的錯誤將幫助我。

+0

[相關](http://stackoverflow.com/q/11497576/179910)。 –

+0

是的。但是我的代碼存在一個我無法找到的錯誤。 – roang

+0

我在C++中訪問地圖值的方式是否正確? – roang

回答

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