-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clone a linked list with next and random pointer
50 lines (43 loc) Β· 1.23 KB
/
Clone a linked list with next and random pointer
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
/* Link list Node
struct Node {
int data;
Node *next;
Node *random;
Node(int x) {
data = x;
next = NULL;
random = NULL;
}
};*/
class Solution {
public:
Node *copyList(Node *head) {
if (!head) return nullptr;
// First pass: Create copy nodes and insert them between original nodes
Node* curr = head;
while (curr) {
Node* copy = new Node(curr->data);
copy->next = curr->next;
curr->next = copy;
curr = copy->next;
}
// Second pass: Assign random pointers for the copy nodes
curr = head;
while (curr) {
if (curr->random)
curr->next->random = curr->random->next;
curr = curr->next->next;
}
// Third pass: Separate the original and copied lists
Node* original = head;
Node* copy = head->next;
Node* copyHead = copy;
while (original && copy) {
original->next = original->next->next;
copy->next = copy->next ? copy->next->next : nullptr;
original = original->next;
copy = copy->next;
}
return copyHead;
}
};