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 118 119 120 121
|
#include <iostream>
using namespace std;
struct node
{
int value;
node *next;
};
bool isEmpty(node *head);
char menu();
void insertAsFirstElement(node *&head, node *&tail, int value);
void insert(node *&head, node *&tail, int value);
void remove(node *&head, node *&tail);
void showList(node *current);
int main()
{
node *head = NULL;
node *tail = NULL;
char choice;
int number;
do {
choice = menu();
switch(choice)
{
case '1': cout << "Please enter a number: ";
cin >> number;
insert(head, tail, number);
break;
case '2': remove(head, tail);
break;
case '3': showList(head);
break;
default : cout << "Exit\n";
}
}while(choice != '4');
return 0;
}
bool isEmpty(node *head)
{
if(head == NULL)
return true;
else
return false;
}
char menu()
{
char choice;
cout << "Menu:\n";
cout << "1. Add a number to the list.\n";
cout << "2. Remove a number from the front of the list.\n";
cout << "3. Show the list.\n";
cout << "4. Exit\n";
cin >> choice;
return choice;
}
void insertAsFirstElement(node *&head, node *&tail, int value)
{
node *temp = new node;
temp->value = value;
temp->next = NULL;
head = temp;
tail = temp;
}
void insert(node *&head, node *&tail, int value)
{
if(isEmpty(head))
insertAsFirstElement(head, tail, value);
else
{
node *temp = new node;
temp->value = value;
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 *current)
{
if(isEmpty(current))
cout << "The list is empty.\n";
else
{
cout << "The list contains: \n";
while(current != NULL)
{
cout << current->value << endl;
current = current->next;
}
}
}
|