-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138_Copy_List_with_Random_Pointer.cpp
62 lines (54 loc) · 1.34 KB
/
138_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
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.
*/
/**
* 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) {}
* };
*/
#include <unordered_map>
using namespace std;
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
unordered_map<long long, RandomListNode*> mp;
RandomListNode *output = NULL;
RandomListNode *temp = output;
//create new list
while(head){
//add to new list
if(output){
temp->next = new RandomListNode(head->label);
temp = temp->next;
}
else{
temp = new RandomListNode(head->label);
output = temp;
}
temp->random = head->random;
//stort to mp
mp[(long long)head] = temp;
//update
head = head->next;
}
//complete new list with random pointer
temp = output;
while(temp){
//redirect random pointer
if(temp->random) temp->random = \
mp[(long long)temp->random];
//update
temp = temp->next;
}
return output;
}
};