Same idea with the Clone Graph. Here I simplify the unordered map to connect two pointer addresses.
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head)
return NULL;
unordered_map<RandomListNode*,RandomListNode*> link;
RandomListNode* phead=new RandomListNode(head->label);
link.insert(make_pair(head,phead));
copy(head,phead,link);
return phead;
}
void copy(RandomListNode* pold,RandomListNode* pnew,unordered_map<RandomListNode*,RandomListNode*>& link)
{
if(!pold)
return;
RandomListNode* p=pold->next;
if(p)
{
if(link.find(p)!=link.end())
pnew->next=link[p];
else
{
pnew->next=new RandomListNode(p->label);
link.insert(make_pair(p,pnew->next));
}
}
p=pold->random;
if(p)
{
if(link.find(p)!=link.end())
pnew->random=link[p];
else
{
pnew->random=new RandomListNode(p->label);
link.insert(make_pair(p,pnew->random));
}
}
copy(pold->next,pnew->next,link);
}
};