TheAlgorithms-C-Plus-Plus/data_structure/linked_list.cpp

136 lines
3.5 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
struct node {
int val;
node *next;
2017-12-24 01:30:49 +08:00
};
node *start;
void insert(int x) {
node *t = start;
2020-04-22 22:09:12 +08:00
node *n = new node;
n->val = x;
n->next = NULL;
if (start != NULL) {
while (t->next != NULL) {
t = t->next;
}
t->next = n;
} else {
start = n;
}
2020-04-22 22:09:12 +08:00
2017-12-24 01:30:49 +08:00
}
void remove(int x) {
if (start == NULL) {
std::cout << "\nLinked List is empty\n";
return;
} else if (start->val == x) {
node *temp = start;
start = start->next;
delete temp;
return;
}
node *temp = start, *parent = start;
2019-01-09 23:01:55 +08:00
while (temp != NULL && temp->val != x) {
parent = temp;
temp = temp->next;
}
2019-01-09 23:01:55 +08:00
if (temp == NULL) {
std::cout << std::endl << x << " not found in list\n";
return;
}
parent->next = temp->next;
delete temp;
2017-12-24 01:30:49 +08:00
}
void search(int x) {
node *t = start;
int found = 0;
while (t != NULL) {
if (t->val == x) {
std::cout << "\nFound";
found = 1;
break;
}
t = t->next;
}
if (found == 0) {
std::cout << "\nNot Found";
}
2017-12-24 01:30:49 +08:00
}
void show() {
node *t = start;
while (t != NULL) {
std::cout << t->val << "\t";
t = t->next;
}
2017-12-24 01:30:49 +08:00
}
void reverse() {
node *first = start;
if (first != NULL) {
node *second = first->next;
while (second != NULL) {
node *tem = second->next;
second->next = first;
first = second;
second = tem;
}
start->next = NULL;
start = first;
} else {
std::cout << "\nEmpty list";
}
2019-08-07 09:34:58 +08:00
}
int main() {
int choice, x;
do {
std::cout << "\n1. Insert";
std::cout << "\n2. Delete";
std::cout << "\n3. Search";
std::cout << "\n4. Print";
std::cout << "\n5. Reverse";
std::cout << "\n0. Exit";
std::cout << "\n\nEnter you choice : ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "\nEnter the element to be inserted : ";
std::cin >> x;
insert(x);
break;
case 2:
std::cout << "\nEnter the element to be removed : ";
std::cin >> x;
remove(x);
break;
case 3:
std::cout << "\nEnter the element to be searched : ";
std::cin >> x;
search(x);
break;
case 4:
show();
std::cout << "\n";
break;
case 5:
std::cout << "The reversed list: \n";
reverse();
show();
std::cout << "\n";
break;
}
} while (choice != 0);
2017-12-24 01:30:49 +08:00
return 0;
2017-12-24 01:30:49 +08:00
}