TheAlgorithms-C-Plus-Plus/Operations on Datastructures/Circular Linked List.cpp

115 lines
1.4 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-12-24 01:30:49 +08:00
using namespace std;
struct node
{
int val;
node *next;
};
node *start;
void insert(int x)
{
2019-08-21 10:10:08 +08:00
node *t = start;
if (start != NULL)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
while (t->next != start)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
t = t->next;
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
node *n = new node;
t->next = n;
n->val = x;
n->next = start;
2017-12-24 01:30:49 +08:00
}
else
{
2019-08-21 10:10:08 +08:00
node *n = new node;
n->val = x;
start = n;
n->next = start;
2017-12-24 01:30:49 +08:00
}
}
void remove(int x)
{
2019-08-21 10:10:08 +08:00
node *t = start;
2017-12-24 01:30:49 +08:00
node *p;
2019-08-21 10:10:08 +08:00
while (t->val != x)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
p = t;
t = t->next;
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
p->next = t->next;
2017-12-24 01:30:49 +08:00
delete t;
}
void search(int x)
{
2019-08-21 10:10:08 +08:00
node *t = start;
int found = 0;
while (t->next != start)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
if (t->val == x)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << "\nFound";
found = 1;
2017-12-24 01:30:49 +08:00
break;
}
2019-08-21 10:10:08 +08:00
t = t->next;
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
if (found == 0)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << "\nNot Found";
2017-12-24 01:30:49 +08:00
}
}
void show()
{
2019-08-21 10:10:08 +08:00
node *t = start;
2017-12-24 01:30:49 +08:00
do
{
2019-08-21 10:10:08 +08:00
cout << t->val << "\t";
t = t->next;
} while (t != start);
2017-12-24 01:30:49 +08:00
}
int main()
{
int choice, x;
do
{
2019-08-21 10:10:08 +08:00
cout << "\n1. Insert";
cout << "\n2. Delete";
cout << "\n3. Search";
cout << "\n4. Print";
cout << "\n\nEnter you choice : ";
cin >> choice;
2017-12-24 01:30:49 +08:00
switch (choice)
{
2019-08-21 10:10:08 +08:00
case 1:
cout << "\nEnter the element to be inserted : ";
cin >> x;
insert(x);
break;
case 2:
cout << "\nEnter the element to be removed : ";
cin >> x;
remove(x);
break;
case 3:
cout << "\nEnter the element to be searched : ";
cin >> x;
search(x);
break;
case 4:
show();
break;
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
} while (choice != 0);
2017-12-24 01:30:49 +08:00
return 0;
}