-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy List with Random Pointer LC-138.cpp
98 lines (87 loc) · 1.85 KB
/
Copy List with Random Pointer LC-138.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Intuitive stuff
// tc=o(n)
// sc=o(n)
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return head;
Node *temp1=head, *temp2;
Node *copy_head;
while(temp1){
temp2=temp1->next;
temp1->next=new Node(temp1->val);
temp1=temp1->next;
temp1->next=temp2;
temp1=temp2;
}
temp1=head;
while(temp1){
temp1->next->random=temp1->random?temp1->random->next:NULL;
temp1=temp1->next->next;
}
copy_head=head->next;
temp1=head;
while(temp1){
temp2=temp1->next;
temp1->next=temp2->next;
temp1=temp1->next;
temp2->next=temp1?temp1->next:NULL;
}
return copy_head;
}
};
// Hashmap
// tc=o(n)
// sc=o(n)
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return NULL;
Node* temp=head;
Node *copy_head=new Node(0);
Node* copy=copy_head;
unordered_map<Node*,Node*> map;
while(temp){
copy->next=new Node(temp->val);
copy=copy->next;
map[temp]=copy;
temp=temp->next;
}
copy=copy_head->next;
temp=head;
while(temp){
copy->random=map[temp->random];
copy=copy->next;
temp=temp->next;
}
return copy_head->next;
}
};