-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCopyListwithRandomPointer_138.cpp
67 lines (54 loc) · 1.56 KB
/
CopyListwithRandomPointer_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
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 138. Copy List with Random Pointer
~ Link : https://leetcode.com/problems/copy-list-with-random-pointer/
*/
/*
// 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 *curr = head;
// creating brand new nodes and connecting it just
// after the current node in the given list
while (curr) {
Node *copyNode = new Node(curr -> val);
copyNode -> next = curr -> next;
curr -> next = copyNode;
curr = curr -> next -> next;
}
curr = head;
// setting the random pointers of the newly created nodes
while (curr) {
curr -> next -> random = ((curr -> random == NULL) ? NULL : curr -> random -> next);
curr = curr -> next -> next;
}
Node *newHead = head -> next, *nextNode;
curr = head;
// restoring the given list and the deep copy list
while (curr) {
nextNode = curr -> next;
curr -> next = nextNode -> next;
curr = curr -> next;
if (curr)
nextNode -> next = curr -> next;
}
return newHead;
}
};
// Time Complexity - O(n)
// Space Complexity - O(1)