#include <iostream.h>
#include <stdlib.h>
#include <string.h>
//enum bool{false, true};
struct list_item
{
char string[50];
list_item* next;
list_item* previous;
};
class list
{
private:
list_item* head; // Ptr to head of list
list_item* tail; // Ptr to tail of list
public:
list(); // Constructor - initialise empty list
bool insert( char* ); // Add string to tail of list
void display(); // Display list
void display_reverse(); // Display list in reverse order
};
list::list() // list constructor
{
head = NULL;
tail = NULL;
}
bool list::insert( char* data )
{
list_item* new_item;
new_item = new list_item;
if ( new_item == NULL )
return false;
strcpy( new_item -> string, data );
if ( head == NULL )
{
tail = new_item;
head = new_item;
new_item -> next = NULL;
new_item -> previous = NULL;
}
else
{
tail -> next = new_item;
new_item -> previous = tail;
new_item -> next = NULL;
tail = new_item;
}
return true;
}
void list::display()
{
list_item* current;
current = head;
if ( current == NULL )
cout << "\n\n Empty list!\n";
else
cout << "\n\n List:\n";
while ( current != NULL )
{
cout << " " << current -> string << "\n";
current = current -> next;
}
}
void list::display_reverse()
{
list_item* current;
current = tail;
if ( current == NULL )
cout << "\n\n Empty list!\n";
else
cout << "\n\n List:\n";
while ( current != NULL )
{
cout << " " << current -> string << "\n";
current = current -> previous;
}
}
void main( void )
{
char string[50];
char choice;
list l;
bool result;
do {
cout << "\n\n Menu:\n\n 1. Add to list\n 2. Print list\n";
cout << " 3. Print list in reverse order\n 4. Quit\n\n Please enter your choice: ";
cin >> choice;
switch( choice )
{
case '1':
cout << "\n Type string to add to list: ";
cin >> string;
result = l.insert( string );
if ( !result )
cout << "\n Insufficient memory!";
break;
case '2':
l.display();
break;
case '3':
l.display_reverse();
break;
}
} while ( choice != '4' );
}
syntax highlighted by Code2HTML, v. 0.8.11