forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClone_of_Linked_List
128 lines (110 loc) · 2.81 KB
/
Clone_of_Linked_List
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
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node* random;
Node(int data){
this->data = data;
this->next = NULL;
this->random = NULL;
}
};
void InsertTail(Node* &head, Node* &tail, int data)
{
Node* newnode = new Node(data);
if(head == NULL){
head = newnode;
tail = newnode;
return;
}
else{
tail->next = newnode;
tail = newnode;
}
}
Node *cloneList(Node *head)
{
// Step 1 :- Create A clone List without random pointer:-
Node* cloneHead = NULL;
Node* cloneTail = NULL;
Node* ptr = head;
while(ptr != NULL){
InsertTail(cloneHead,cloneTail,ptr->data);
ptr = ptr->next;
}
// Step 2:- Clone Nodes Add in-between Original Node:-
Node* originalNode = head;
Node* cloneNode = cloneHead;
while(originalNode != NULL && cloneNode != NULL){
Node* foreward = originalNode->next;
originalNode->next = cloneNode;
originalNode = foreward;
foreward = cloneNode->next;
cloneNode->next = originalNode;
cloneNode = foreward;
}
// Step 3 :- Copy Random pointer of original pointer in Clone LL:-
Node* temp = head;
while(temp != NULL){
if(temp->next != NULL){
if(temp->random != NULL){
temp->next->random = temp->random->next;
}
else{
temp->next->random = temp->random;
}
}
temp = temp->next->next;
}
// Step 4 :- Revert Changes done in Step 2 :-
originalNode = head;
cloneNode = cloneHead;
while(originalNode != NULL && cloneNode != NULL){
originalNode->next = cloneNode->next;
originalNode = originalNode->next;
if(originalNode != NULL){
cloneNode->next = originalNode->next;
}
cloneNode = cloneNode->next;
}
// Step 5 :- Return Clone Head:-
return cloneHead;
}
void display(Node* head){
Node* ptr = head;
while(ptr != NULL){
cout<<ptr->data<<" ";
ptr = ptr->next;
}cout<<endl;
}
void random_ptr_check(Node* head){
Node* ptr = head;
while(ptr != NULL){
if(ptr->random == NULL){
cout<<"0 "<<" ";
}
else{
cout<<ptr->random->data<<" ";
}
ptr = ptr->next;
}cout<<endl;
}
int main(){
Node* head = NULL;
Node* first = new Node(1);
Node* second = new Node(2);
Node* third = new Node(3);
head = first;
first->next = second;
second->next = third;
first->random = third;
second->random = first;
display(head);
random_ptr_check(head);
Node* head2 = cloneList(head);
display(head2);
random_ptr_check(head2);
return 0;
}