-
Notifications
You must be signed in to change notification settings - Fork 32
/
linkedlist.cpp
117 lines (117 loc) · 1.96 KB
/
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
#include <iostream>
using namespace std;
struct node
{
int num;
node *next;
}
bool isEmpty(node *head);
char menu();
void insertAsFirst(node *head, node *last, int number);
void insert(node *head, node *last, int number);
void remove(node *head, node *last);
void display(node *current);
bool isEmpty(node *head)
{
if(head == NULL)
{
return true;
}
else
{
return false;
}
}
char menu()
{
char choice;
cout << "Menu:"
cout << "1. Add an item:\n";
cout << "2. Remove an item.\n";
cout << "3. Show the list.\n";
cout << "4. exit";
cin >> choice;
return choice;
}
void insertAsFirst(node *head, node *last, int number)
{
node *temp = new node;
temp->num = number;
temp->next = NULL;
head = temp;
last = temp;
}
void insert(node *head, node *last, int number)
{
if(isEmpty(head)==true)
{
insertAsFirst(head, last, number)
}
else
{
node *temp = new node;
temp->num = number;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void remove(node *head, node *last)
{
if(isEmpty(head))
{
cout << "The list is already Empty";
}
else if (head == last)
{
delete head;
head = NULL;
last = NULL;
}
else
{
node *temp = head;
head = head->next;
delete temp;
}
}
void display(node *current)
{
if(isEmpty())
{
cout << "The list is empty";
}
else
{
cout << "The list contains: \n";
while(current!=NULL)
{
cout << current->num << end1;
current = current->next;
}
}
}
int main()
{
node *head = NULL;
node *last = NULL;
char choice;
int number;
do
{
choice = menu();
switch(choice)
{
case '1': cout << "Please enter a number:";
cin >> number;
insert(head,last,number);
break;
case '2': remove(head,last);
break;
case '3': display(head);
break;
default: cout << "System exit";
}
}(while choice!='4')
return 0;
}