码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Copy List with Random Pointer

时间:2015-07-14 13:21:33      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!