-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy List with Random Pointer.cpp
More file actions
52 lines (45 loc) · 1.15 KB
/
Copy pathCopy List with Random Pointer.cpp
File metadata and controls
52 lines (45 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
Node* curr = head;
while (curr) {
Node* new_node = new Node(curr->val);
new_node->next = curr->next;
curr->next = new_node;
curr = new_node->next;
}
curr = head;
while (curr) {
if (curr->random) {
curr->next->random = curr->random->next;
}
curr = curr->next->next;
}
Node* old_head = head;
Node* new_head = head->next;
Node* curr_old = old_head;
Node* curr_new = new_head;
while (curr_old) {
curr_old->next = curr_old->next->next;
curr_new->next = curr_new->next ? curr_new->next->next : nullptr;
curr_old = curr_old->next;
curr_new = curr_new->next;
}
return new_head;
}
};