File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Filter options
February Leetcode Challenge 2021 Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ Node* copyRandomList (Node* head) {
4
+
5
+ // STEP 1: PASS 1
6
+ // Creating a copy (except random pointer) of each old node and insert it next to the old node it's copied from.
7
+ // That is, it will create new alternative nodes which are a copy (except random pointer) of its previous node.
8
+ Node* node=head;
9
+ while (node){
10
+ Node* temp=node->next ;
11
+ node->next =new Node (node->val );
12
+ node->next ->next =temp;
13
+ node=temp;
14
+ }
15
+
16
+ // STEP 2: PASS 2
17
+ // Now copy the random pointer (if exists) of the old nodes to their copy new nodes.
18
+ node=head;
19
+ while (node){
20
+ if (node->random )
21
+ node->next ->random =node->random ->next ;
22
+ node=node->next ->next ; // go to next old node
23
+ }
24
+
25
+ // STEP 3: PASS 3
26
+ // Copy the alternative nodes into "ans" link list using the "helper" pointer along with restoring the old link list.
27
+ Node* ans=new Node (0 ); // first node is a dummy node
28
+ Node* helper=ans;
29
+
30
+ while (head){
31
+ // Copy the alternate added nodes from the old linklist
32
+ helper->next =head->next ;
33
+ helper=helper->next ;
34
+
35
+ // Restoring the old linklist, by removing the alternative newly added nodes
36
+ head->next =head->next ->next ;
37
+ head=head->next ; // go to next alternate node
38
+ }
39
+ return ans->next ; // Since first node is a dummy node
40
+ }
41
+ };
You can’t perform that action at this time.
0 commit comments