-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy_List_with_Random_Pointer.cpp
46 lines (41 loc) · 1.33 KB
/
Copy_List_with_Random_Pointer.cpp
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
35
36
37
38
39
40
41
42
43
44
45
46
/**
* 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) return head;
unordered_map <RandomListNode*, RandomListNode*> Map;
RandomListNode *head2 = new RandomListNode(head->label);
Map[head] = head2;
RandomListNode *newHead = head2;
RandomListNode *next, *random;
while(head) {
next = head->next, random = head->random;
if(next) {
if(!Map[next]) {
head2->next = new RandomListNode(next->label);
Map[next] = head2->next;
} else {
head2->next = Map[next];
}
}
if(random) {
if(!Map[random]) {
head2->random = new RandomListNode(random->label);
Map[random] = head2->random;
} else {
head2->random = Map[random];
}
}
head2 = head2->next;
head = next;
}
return newHead;
}
};