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

138. Copy List with Random Pointer

时间:2015-01-18 16:57:31      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

 1 RandomListNode *copyRandomList(RandomListNode *head) 
 2     {
 3         unordered_map<RandomListNode *, RandomListNode *> listMap;
 4         RandomListNode *dummy = new RandomListNode(0), *oldNode, *newNode, *r;
 5         
 6         r = dummy;
 7         for (oldNode = head; oldNode != NULL; oldNode = oldNode->next)
 8         {
 9             newNode = new RandomListNode(oldNode->label);
10             listMap[oldNode] = newNode;
11             r->next = newNode;
12             r = newNode;
13         }
14         
15         for (oldNode = head; oldNode != NULL; oldNode = oldNode->next)
16             listMap[oldNode]->random = listMap[oldNode->random];
17         
18         r = dummy->next;
19         delete dummy;
20         return r;
21     }

 

138. Copy List with Random Pointer

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4231827.html

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