1 /** 2 * Definition for singly-linked list with a random pointer. 3 * struct RandomListNode { 4 * int label; 5 * RandomListNode *next, *random; 6 * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 RandomListNode *copyRandomList(RandomListNode *head) { 12 13 if (head == NULL) return NULL; 14 RandomListNode *result = new RandomListNode(head->label), *next, *random; 15 16 unordered_map<RandomListNode*, RandomListNode*> dict; 17 dict[head] = result; 18 19 while (head){ 20 21 if (head->random){ 22 23 if (dict[head->random]) dict[head]->random = dict[head->random]; 24 else{ 25 dict[head->random] = new RandomListNode(head->random->label); 26 dict[head]->random = dict[head->random]; 27 } 28 } 29 30 if (head->next){ 31 32 if (dict[head->next]) dict[head]->next = dict[head->next]; 33 else{ 34 dict[head->next] = new RandomListNode(head->next->label); 35 dict[head]->next = dict[head->next]; 36 } 37 } 38 head = head->next; 39 } 40 return result; 41 } 42 };