Skip to content

Commit fa26caa

Browse files
Create copy_list_with_random_ptr.cpp
1 parent c9f565a commit fa26caa

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

copy_list_with_random_ptr.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
public:
5+
int val;
6+
Node* next;
7+
Node* random;
8+
9+
Node(int _val) {
10+
val = _val;
11+
next = NULL;
12+
random = NULL;
13+
}
14+
};
15+
*/
16+
17+
class Solution {
18+
public:
19+
Node* copyRandomList(Node* head) {
20+
21+
auto current_node = head;
22+
map<Node*, Node*> mp;
23+
24+
//step 1: copy nodes
25+
while(current_node) {
26+
mp[current_node] = new Node(current_node->val);
27+
current_node = current_node->next;
28+
}
29+
30+
//step 2: fix random and next pointers
31+
current_node = head;
32+
while(current_node) {
33+
mp[current_node]->next = mp[current_node->next];
34+
mp[current_node]->random = mp[current_node->random];
35+
current_node = current_node->next;
36+
}
37+
return mp[head];
38+
}
39+
};

0 commit comments

Comments
 (0)