Simple understandable C++ solution


#1

RandomListNode* Solution::copyRandomList(RandomListNode* A)
{
map<int,RandomListNode*>m;
map<RandomListNode*,int>index;
RandomListNode* new_head=NULL;
RandomListNode* prev,tmp;
tmp=A;
int i=0;
while(tmp!=NULL)
{
RandomListNode
new_node=new RandomListNode(tmp->label);
if(new_head==NULL)
{
new_head=new_node;
}
else
{
prev->next=new_node;
}
prev=new_node;
index[tmp]=i;
m[i]=new_node;
i++;
tmp=tmp->next;
}
tmp=A;
RandomListNode* h=new_head;
while(tmp!=NULL && h!=NULL)
{
if(index.find(tmp->random)!=index.end())
{
int x=index[tmp->random];
h->random=m[x];
}
h=h->next;
tmp=tmp->next;
}
return new_head;
}