-
Notifications
You must be signed in to change notification settings - Fork 46
/
DeepCopyLL.cpp
55 lines (36 loc) · 1.39 KB
/
DeepCopyLL.cpp
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
53
54
55
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
Node* random;
Node(int data) : data(data), next(NULL), random(NULL) {}
};
Node* clone(Node* head){
if(head == NULL) return NULL;
Node* travellingPtr = head;
// Insert clone node of n-th node between original n-th node and (n + 1)-th node
while(travellingPtr){
Node* temp = travellingPtr->next;
travellingPtr->next = new Node(travellingPtr->data);
travellingPtr->next->next = temp;
travellingPtr = temp;
}
travellingPtr = head;
// Clone random pointer of clone nodes
while(travellingPtr) {
if(travellingPtr->next)
travellingPtr->next->random = travellingPtr->random? travellingPtr->random->next: travellingPtr->random;
travellingPtr = travellingPtr->next? travellingPtr->next->next: travellingPtr->next;
}
Node* originalHead = head, *cloneHead = head->next, *finalPtr = head->next;
// Split it into two list, which will produce additional copy of original List
while(originalHead && cloneHead) {
originalHead->next = (originalHead->next? originalHead->next->next : originalHead->next);
cloneHead->next = (cloneHead->next? cloneHead->next->next: cloneHead->next);
originalHead = originalHead->next;
cloneHead = cloneHead->next;
}
return finalPtr;
}