forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Circular_Linked_List.cpp
167 lines (142 loc) · 3.14 KB
/
Circular_Linked_List.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
node *last;
/**** Create Circular Link List ****/
void create_node(int value)
{
node *temp;
temp = new node;
temp->data = value;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}
/**** Insertion of element at a particular place ****/
void Insertion(int value, int pos)
{
if (last == NULL)
return;
node *temp, *s;
s = last->next;
for (int i = 1; i < pos; i++)
{
s = s->next;
if (s == last->next)
return;
}
temp = new node;
temp->next = s->next;
temp->data = value;
s->next = temp;
if (s == last) // Element inserted at the end
{
last = temp;
}
}
/**** Deletion of element from the list ****/
void Deletion(int value)
{
struct node *temp, *s;
s = last->next;
if (last->next == last && last->data == value) // One element is there
{
temp = last;
last = NULL;
delete temp;
return;
}
if (s->data == value) // First Element Deletion
{
temp = s;
last->next = s->next;
delete temp;
return;
}
while (s->next != last)
{
if (s->next->data == value) // Deletion in between of list
{
temp = s->next;
s->next = temp->next;
delete temp;
return;
}
s = s->next;
}
if (s->next->data == value) // Deletion of last element
{
temp = s->next;
s->next = last->next;
delete temp;
last = s;
return;
}
cout << "Not found in the list" << endl;
}
/**** Search element in the list ****/
void Search(int value)
{
node *s;
int position = 0;
s = last->next;
while (s != last)
{
position++;
if (s->data == value)
{
cout << "Found at :" << position << endl;
return;
}
s = s->next;
}
if (s->data == value)
{
position++;
cout << "Found at :" << position << endl;
return;
}
cout << "Not found in the list" << endl;
}
/**** Print Circular Link List ****/
void Print()
{
node *s;
if (last == NULL)
return; // Empty list
s = last->next;
while (s != last)
{
cout<<s->data<<" -> ";
s = s->next;
}
cout << s->data << endl;
}
int main()
{
create_node(5);
Print(); // 5
create_node(3);
Print(); // 5 -> 3
create_node(9);
Print(); // 5 -> 3 -> 9
Insertion(1, 2);
Print(); // 5 -> 3 -> 1 -> 9
Search(1); // Found at 3
Search(4); // Not found in the list
Deletion(1);
Print(); // 5 -> 3 -> 9
return 0;
}