-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path138. Copy List with Random Pointer.cpp
78 lines (72 loc) · 1.82 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
/********************* Method-1 ( Using Hash Table, i.e. Map) *****************
// TC - O(N) assuming Map access is O(1) avg.
// SC - O(N) for Map and new List
class Solution {
public:
Node* copyRandomList(Node* head) {
map<Node*, Node*> m;
Node* ptr = head;
while (ptr) {
m[ptr] =new Node(ptr->val);
ptr = ptr->next;
}
ptr = head;
while(ptr) {
m[ptr]->next = m[ptr->next];
m[ptr]->random = m[ptr->random];
ptr = ptr->next;
}
return m[head];
}
};
**************************************************************************/
/**************** Method - 2 (Without Map) *************************/
// Simple Linked-List only solution
// TC - O(N)
// SC - O(N) for new Linked List
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) {
return NULL;
}
Node *temp = head;
Node *copyNode = NULL;
while(temp) {
copyNode = new Node(temp->val);
copyNode->next = temp->next;
temp->next = copyNode;
temp = copyNode->next;
}
temp = head;
while(temp) {
copyNode = temp->next;
if(temp->random)
copyNode->random = temp->random->next;
temp = copyNode->next;
}
Node* res = head->next;
temp = head;
while(temp) {
copyNode = temp->next;
temp->next = copyNode->next;
temp = temp->next;
if(temp) copyNode->next = temp->next;
}
return res;
}
};