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

LeetCode OJ:Copy List with Random Pointer(复制存在随机链接的链表)

时间:2015-12-28 21:52:33      阅读:162      评论: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.

这题用map做其实比较简单,但是一开始没想明白越想越乱,最后看了下别人的实现,思路还是很清晰的,代码如下所示:

 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 
10 class Solution {
11 public:
12     RandomListNode *copyRandomList(RandomListNode *head) {
13         unordered_map<RandomListNode *, RandomListNode *> m;
14         RandomListNode helper1(0), * p1 = &helper1, helper2(0), *p2 = &helper2;
15         p1->next = head;
16         while(p1->next){
17             p1 = p1->next;
18             RandomListNode * tmpNode = new RandomListNode(p1->label);
19             m[p1] = tmpNode;
20             p2 = p2->next = tmpNode;
21         }
22         p1 = &helper1;
23         while(p1->next){
24             p1 = p1->next;
25             if(p1->random){
26                 m[p1]->random = m[p1->random];
27             }
28         }
29         return helper2.next;
30     }
31 };

 

LeetCode OJ:Copy List with Random Pointer(复制存在随机链接的链表)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4993046.html

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