Copy List with Random Pointer LeetCode solution in C++

1
class Solution {
2
public:
3
Node *copyRandomList(Node *head) {
4
if (head == NULL) {
5
return NULL;
6
}
7

8
Node *temp = head;
9
while (temp != NULL) {
10
Node *m = new Node(temp->val);
11
m->next = temp->next;
12
temp->next = m;
13
temp = temp->next->next;
14
}
15
temp = head;
16
while (temp != NULL) {
17
if (temp->random == NULL) {
18
temp->next->random = NULL;
19
} else {
20
temp->next->random = temp->random->next;
21
}
22

23
temp = temp->next->next;
24
}
25
temp = head;
26
Node *p = new Node(-1);
27
Node *r = p;
28
Node *q = head;
29
while (q != NULL) {
30
q = q->next->next;
31
p->next = temp->next;
32
p = p->next;
33
temp->next = q;
34
temp = temp->next;
35
}
36
p->next = NULL;
37

38
return r->next;
39
}
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0