forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0138.cpp
More file actions
executable file
·43 lines (38 loc) · 831 Bytes
/
LC0138.cpp
File metadata and controls
executable file
·43 lines (38 loc) · 831 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/copy-list-with-random-pointer/
Time: O(n)
Space: O(1)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
Node *head2, *temp1, *temp2;
// clone nodes of linked list
temp1 = head;
while (temp1) {
temp2 = new Node(temp1->val);
temp2->next = temp1->next;
temp1->next = temp2;
temp1 = temp2->next;
}
head2 = (head) ? head->next : nullptr;
// assign random pointers
temp1 = head;
while (temp1) {
temp2 = temp1->next;
if (temp1->random)
temp2->random = temp1->random->next;
temp1 = temp2->next;
}
// undo rewirings
temp1 = head;
while (temp1) {
temp2 = temp1->next;
if (temp2)
temp1->next = temp2->next;
temp1 = temp2;
}
return head2;
}
};