-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path038_Copy List with Random Pointer.cpp
94 lines (67 loc) · 1.94 KB
/
038_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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// TC -> O(N) + O(N) = O(2N) ~ O(N)
// SC -> O(N)
LinkedListNode<int> *cloneRandomList(LinkedListNode<int> *head)
{
// Write your code here.
unordered_map<LinkedListNode<int>*, LinkedListNode<int>*> mp;
LinkedListNode<int>* ptr = head, *dummy = new LinkedListNode<int>(0), *res = dummy;
while(ptr)
{
res->next = new LinkedListNode<int>(ptr->data);
res = res->next;
mp[ptr] = res;
ptr = ptr->next;
}
ptr = head;
while(ptr)
{
mp[ptr]->next = ptr->next;
mp[ptr]->random = ptr->random;
ptr = ptr->next;
}
return dummy->next;
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// TC -> O(N) + O(N) + O(N) = O(3N) ~ O(N)
// SC -> O(1)
LinkedListNode<int> *cloneRandomList(LinkedListNode<int> *head)
{
// Write your code here.
LinkedListNode<int> *dummy = new LinkedListNode<int>(0), *temp = head, *res = dummy;
while(temp)
{
LinkedListNode<int> * ptr = new LinkedListNode<int>(temp->data);
LinkedListNode<int> *nex;
if(temp->next)
nex = temp->next;
else
nex = nullptr;
temp->next = ptr;
ptr->next = nex;
temp = nex;
}
temp = head;
// while(temp)
// {
// cout<<temp->data<<' ';
// temp = temp->next;
// }
while(temp)
{
if(temp->random)
temp->next->random = temp->random->next;
else
temp->next->random = nullptr;
temp = temp->next->next;
}
temp = head;
while(temp)
{
LinkedListNode<int> *nex = temp->next;
temp->next = nex->next;
res->next = nex;
res = res->next;
temp = temp->next;
}
return dummy->next;
}