标签:
Well, since we need to make a deep copy of the list and nodes in the list have a random pointer that may point to any node in the list (or NULL), we need to maintain a mapping from each node in the origianl list to the node in the copy list. If the copy of a node already exists, just use that copy without copying it again; otherwise, create a new copy and add it to the mapping.
The following code is pretty straight-forward.
1 class Solution { 2 public: 3 RandomListNode *copyRandomList(RandomListNode *head) { 4 if (!head) return NULL; 5 unordered_map<RandomListNode*, RandomListNode*> mp; 6 RandomListNode* new_head = new RandomListNode(head -> label); 7 mp[head] = new_head; 8 RandomListNode* run = head; 9 RandomListNode* new_run = new_head; 10 while (run) { 11 // Process the next pointer 12 if (run -> next) { 13 if (mp.find(run -> next) != mp.end()) 14 new_run -> next = mp[run -> next]; 15 else { 16 new_run -> next = new RandomListNode(run -> next -> label); 17 mp[run -> next] = new_run -> next; 18 } 19 } 20 // Process the random pointer 21 if (run -> random) { 22 if (mp.find(run -> random) != mp.end()) 23 new_run -> random = mp[run -> random]; 24 else { 25 new_run -> random = new RandomListNode(run -> random -> label); 26 mp[run -> random] = new_run -> random; 27 } 28 } 29 run = run -> next; 30 new_run = new_run -> next; 31 } 32 return new_head; 33 } 34 };
[LeetCode] Copy List with Random Pointer
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4645132.html