Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit edfcc29

Browse filesBrowse files
authored
Create 10 copyListRandomPtr.cpp
1 parent 8b96704 commit edfcc29
Copy full SHA for edfcc29

File tree

Expand file treeCollapse file tree

1 file changed

+41
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+41
-0
lines changed
+41Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.