forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyRandomList.cpp
More file actions
34 lines (34 loc) · 961 Bytes
/
copyRandomList.cpp
File metadata and controls
34 lines (34 loc) · 961 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) return head;
map<RandomListNode*, RandomListNode*> mp;
RandomListNode* res = new RandomListNode(0);
RandomListNode* p = head;
RandomListNode* q = res;
while (p) {
RandomListNode* t = new RandomListNode(p->label);
q->next = t;
mp[p] = t;
p = p->next;
q = q->next;
}
p = head;
q = res->next;
while (p) {
if (p->random == NULL) q->random = NULL;
else q->random = mp[p->random];
p = p->next;
q = q->next;
}
return res->next;
}
};