-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clone-a-Linked-List-with-random-and-next-pointer.cpp
132 lines (81 loc) · 2.66 KB
/
Clone-a-Linked-List-with-random-and-next-pointer.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node *random;
Node() : data(0), next(nullptr), random(nullptr){};
Node(int x) : data(x), next(nullptr), random(nullptr) {}
Node(int x, Node *nextNode, Node *randomNode) :
data(x), next(nextNode), random(randomNode) {}
};
void insertCopyInBetween(Node* head){
Node* temp = head;
while(temp != NULL){
Node* nextElement = temp->next;
Node* copy = new Node(temp->data);
copy->next = nextElement;
temp->next = copy;
temp = nextElement;
}
}
void connectRandomPointers(Node* head){
Node* temp = head;
while(temp != NULL){
Node* copyNode = temp->next;
if(temp->random){
copyNode->random = temp->random->next;
}
else{
copyNode->random = NULL;
}
temp = temp->next->next;
}
}
Node* getDeepCopyList(Node* head){
Node* temp = head;
Node* dummyNode = new Node(-1);
Node* res = dummyNode;
while(temp != NULL){
res->next = temp->next;
res = res->next;
temp->next = temp->next->next;
temp = temp->next;
}
return dummyNode->next;
}
Node *cloneLL(Node *head){
if(!head) return nullptr;
insertCopyInBetween(head);
connectRandomPointers(head);
return getDeepCopyList(head);
}
void printClonedLinkedList(Node *head) {
while (head != nullptr) {
cout << "Data: " << head->data;
if (head->random != nullptr) {
cout << ", Random: " << head->random->data;
} else {
cout << ", Random: nullptr";
}
cout << endl;
head = head->next;
}
}
int main() {
Node* head = new Node(7);
head->next = new Node(14);
head->next->next = new Node(21);
head->next->next->next = new Node(28);
head->random = head->next->next;
head->next->random = head;
head->next->next->random = head->next->next->next;
head->next->next->next->random = head->next;
cout << "Original Linked List with Random Pointers:" << endl;
printClonedLinkedList(head);
Node* clonedList = cloneLL(head);
cout << "\nCloned Linked List with Random Pointers:" << endl;
printClonedLinkedList(clonedList);
return 0;
}