forked from piyush01123/Daily-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsol.cpp
88 lines (76 loc) · 2.13 KB
/
sol.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <vector>
struct node{
int data;
node *next;
node *random;
};
node *createNode(int data){
node *temp = new node;
temp->data = data;
temp->next = NULL;
temp->random = NULL;
return temp;
}
void printLinkedList(node *head){
//prints linked list
std::cout << "PRINTING" << std::endl;
while (head!=NULL){
std::cout << "Data = "<< head->data << " Random = "<< head->random->data << std::endl;
head = head->next;
}
}
node *deepClone(node *start){
node* curr = start, *temp;
while (curr){
temp = curr->next;
curr->next = createNode(curr->data);
curr->next->next = temp;
curr = temp;
}
// start = 1->1->2->2->3->3->4->4->5->5->6->6
// now copy the random links like 1->1->random = 1->random->next(same as random)
curr = start;
while (curr){
if(curr->next) curr->next->random = curr->random?curr->random->next:\
curr->random;
curr = curr->next?curr->next->next:curr->next;
}
node *original = start;
node *copy = start->next;
// save the start of copied linked list
temp = copy;
// now separate the original list and copied list
while (original && copy){
original->next =
original->next? original->next->next : original->next;
copy->next = copy->next?copy->next->next:copy->next;
original = original->next;
copy = copy->next;
}
return temp;
}
void test(){
std::vector<int> v {1,2,3,4,5,6};
node *head = createNode(v[0]);
node *curr = head;
for (int i=1; i<v.size(); i++){
curr->next = createNode(v[i]);
curr = curr->next;
}
head->random = head->next->next; //1->3
head->next->random = head; //2->1
head->next->next->random = head->next->next->next; //3->4
head->next->next->next->random = head->next; //4->2
head->next->next->next->next->random = head->next->next->next->next->next; //5->6
head->next->next->next->next->next->random = head->next->next->next->next; //6->5
printLinkedList(head);
node *head2 = deepClone(head);
std::cout << "______________________" << '\n';
printLinkedList(head2);
std::cout << "______________________" << '\n';
}
int main(){
test();
return 0;
}