File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments