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