TheAlgorithms-C-Plus-Plus/Data Structure/Doubly Linked List.cpp

135 lines
1.7 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 *prev;
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 != NULL)
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->prev = t;
n->val = x;
n->next = NULL;
2017-12-24 01:30:49 +08:00
}
else
{
2019-08-21 10:10:08 +08:00
node *n = new node;
n->val = x;
n->prev = NULL;
n->next = NULL;
start = n;
2017-12-24 01:30:49 +08:00
}
}
void remove(int x)
{
2019-08-21 10:10:08 +08:00
node *t = start;
while (t->val != x)
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
t->prev->next = t->next;
t->next->prev = t->prev;
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 != NULL)
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;
while (t != NULL)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << t->val << "\t";
t = t->next;
2017-12-24 01:30:49 +08:00
}
}
void reverseShow()
{
2019-08-21 10:10:08 +08:00
node *t = start;
while (t->next != NULL)
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
while (t != NULL)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << t->val << "\t";
t = t->prev;
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. Forward print";
cout << "\n5. Reverse 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;
case 5:
reverseShow();
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;
}