Skip to content

Commit 3ee6c42

Browse files
authored
Create 138. Copy List with random pointer
Here is the solution in C++ without using mapping
0 parents  commit 3ee6c42

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

138. Copy List with random pointer

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Here is the solution of this question without using map
2+
// It's is much optimized
3+
4+
solution in C++
5+
6+
class Solution {
7+
public:
8+
Node* copyRandomList(Node* head) {
9+
if(!head) return 0;
10+
// step 1: clone a -> a'
11+
Node* it = head;
12+
while(it){
13+
Node*clonedNode = new Node(it->val);
14+
clonedNode->next = it->next;
15+
it->next = clonedNode;
16+
it = it->next->next;
17+
18+
}
19+
//step 2: assign random links of A with the help of random pouinter
20+
it = head;
21+
while(it){
22+
Node*clonedNode = it->next;
23+
clonedNode->random = it->random ? it->random->next : nullptr;
24+
it = it->next->next;
25+
}
26+
//step 3: detatch A from A
27+
it = head;
28+
Node*clonedHead = it->next;
29+
while(it){
30+
Node*clonedNode = it->next;
31+
it->next = it->next->next;
32+
if(clonedNode->next){
33+
clonedNode->next = clonedNode->next->next;
34+
35+
}
36+
it = it->next;
37+
}
38+
return clonedHead;
39+
}
40+
};

0 commit comments

Comments
 (0)