-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked-lists.cpp
103 lines (92 loc) · 2.22 KB
/
linked-lists.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
#include<iostream>
using namespace std;
struct node {
int number;
node *next;
};
bool isEmpty(node *head);
char menu();
void insertAsFirstElement(node *&head, node *&tail, int number);
void insert(node *&head, node *&tail, int number);
void remove(node *&head, node *&tail);
void showlist(node *¤t);
bool isEmpty(node *head) {
if (head == NULL)
return true;
else
return false;
}
char menu() {
char choice;
cout << "Menu\n";
cout << "1. Add an item\n";
cout << "2. Remove an item\n";
cout << "3. Show the list\n";
cout << "4. Exit\n";
cin >> choice;
return choice;
}
void insertAsFirstElement(node *&head, node *&tail, int number){
node *temp = new node;
temp->number = number;
temp->next = NULL;
head = temp;
tail = temp;
}
void insert(node *&head, node *&tail, int number) {
if (isEmpty(head))
insertAsFirstElement(head, tail, number);
else {
node *temp = new node;
temp->number = number;
temp->next = NULL;
tail->next = temp;
tail = temp;
}
}
void remove(node *&head, node *&tail) {
if (isEmpty(head))
cout << "The list is already empty\n"
else if (head == tail) {
delete head;
head = NULL;
tail = NULL;
}
else {
node *temp = head;
head = head->next;
delete temp;
}
}
void showlist(node *¤t) {
if (isEmpty(current))
cout << "The list is empty\n"
else {
cout << "The list contains: \n";
while (current != NULL) {
cout << current->number << endl;
current = current->next;
}
}
}
int main() {
node *head = NULL
node *tail = NULL
char choice;
int number;
do {
choice = menu();
switch (choice) {
case '1': cout << "Please insert a number: ";
cin >> number;
insert(head, last, number);
break;
case '2': remove(head, last);
break;
case '3': showlist(head);
break;
default: cout << "System Exit\n";
}
} while (choice != '4');
return 0;
}