首页 > 其他 > 详细

Copy List with Random Pointer

时间:2014-04-25 04:53:38      阅读:354      评论: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.
 
Solution: Solution 1 uses constant extra space.
bubuko.com,布布扣
 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         if (!head) return NULL;
13         unordered_map<RandomListNode *, RandomListNode *> map;
14         RandomListNode dummy(0), *curNew = &dummy, *cur = head;
15         while (cur) 
16         {
17             if (map.find(cur) == map.end())
18                 map[cur] = new RandomListNode(cur->label);
19             if (cur->random && map.find(cur->random) == map.end())
20                 map[cur->random] = new RandomListNode(cur->random->label);
21             curNew->next = map[cur];
22             curNew = curNew->next;
23             curNew->random = map[cur->random];
24             cur = cur->next;
25         }
26         return dummy.next;
27     }
28 };
bubuko.com,布布扣

 

Copy List with Random Pointer,布布扣,bubuko.com

Copy List with Random Pointer

原文:http://www.cnblogs.com/zhengjiankang/p/3682336.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!