forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Circular_LinkedList.cpp
153 lines (138 loc) · 2.62 KB
/
Circular_LinkedList.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
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *next;
//constructor
node(int d)
{
data = d;
next = NULL;
}
};
//Function to insert in circular LinkedList
void insert(node *&head, int data) //pass by referance
{
node *n = new node(data);
n->next = head; //creating a new node
node *temp = head;
if (temp != NULL)
{
while (temp->next != head)
{
temp = temp->next;
}
temp->next = n;
}
//self loop for single node
else
{
n->next = n;
}
head = n;
}
//Creating a function to get the node to be deleted
node *getnode(node *head, int data) //pass ny value
{
node *temp = head;
while (temp->next != head)
{
if (temp->data == data)
{
return temp;
}
temp = temp->next;
}
if (temp->data == data)
{
return temp;
}
return NULL;
}
//Creating the delete function
void del(node *head, int data)
{
node *del = getnode(head, data);
if (del == NULL)
{
return;
}
if (head == del)
{
head = head->next;
}
node *temp = head;
while (temp->next != del)
{
temp = temp->next;
}
temp->next = del->next;
delete del;
}
//function to print circular linkedlist
void print(node *head)
{
node *temp = head;
while (temp->next != head)
{
cout << temp->data << " -> ";
temp = temp->next;
}
cout << temp->data << endl; //for last node
}
int main()
{
node *head = NULL;
cout << "Insertion in circular linkedlist" << endl;
int arr[100], arr2[100];
int n, n2;
cout << "enter the number of elements" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "enter element number " << i << "-" << endl;
cin >> arr[i];
insert(head, arr[i]);
}
cout << "Elements inserted" << endl;
print(head);
cout << "enter the number of elements you want to delete" << endl;
cin >> n2;
for (int j = n2 - 1 + 1; j > 0; j--)
{
cout << "enter position of number " << endl;
cin >> arr2[j];
del(head, arr[j + 1]);
}
print(head);
return 0;
}
/*
OUTPUT
Insertion in circular linkedlist
enter the number of elements
6
enter element number 0-
1
enter element number 1-
2
enter element number 2-
3
enter element number 3-
4
enter element number 4-
5
enter element number 5-
6
Elements inserted
6 -> 5 -> 4 -> 3 -> 2 -> 1
enter the number of elements you want to delete
2
enter position of number
2
enter position of number
3
6 -> 5 -> 2 -> 1
*/