List.cpp

 //---------------------------------------
//
// "List class definition"
//
// List.cpp
//
//---------------------------------------
#include <iostream.h>
#include "list1.h"

//---------------------------------------
//
// Constructor
//
List::List()
{
headPtr = NULL;
tailPtr = 0;
}

//---------------------------------------
//
// Destructor
//
List::~List()
{
if (!isEmpty()){

Node *currentPtr = headPtr, *trash;

while (currentPtr != 0)
trash = currentPtr;
currentPtr = currentPtr->nextPtr;
delete trash;
}

}

//---------------------------------------
//
// This function inserts an item
// specified by the user to the list.
//
void List::Insert(int item)
{
Node *newPtr = new Node(item);

if (isEmpty())
headPtr = tailPtr = newPtr;
else{
newPtr->nextPtr = headPtr;
headPtr = newPtr;
}
}

//---------------------------------------------
//
// This function deletes an item
// specified by the user from the list.
//
void List::Delete(int item)
{

Node *trash, *currentPtr = headPtr->nextPtr, *previousPtr = headPtr;

if (item == headPtr->data){
trash = headPtr;
headPtr = headPtr->nextPtr;
delete trash;
}
else{

while (currentPtr != NULL && currentPtr->data != item){
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;

}
if (currentPtr != NULL){
trash = currentPtr;
previousPtr->nextPtr = currentPtr->nextPtr;
delete trash;

}

}

}

//---------------------------------------
//
// This function prints the contents
// of the list.
//
void List::Print() const
{
if (isEmpty()){
cout << "The list is empty.\n\n";
return;
}

Node *currentPtr = headPtr;

cout << "The list is: ";

while (currentPtr != NULL && currentPtr != 0){
cout << currentPtr->data << ' ';
currentPtr = currentPtr->nextPtr;
}
cout << "\n\n";

}

//---------------------------------------
//
// Checks if the list is empty
//
bool List::isEmpty() const
{
return headPtr == NULL;
}

Project Homepage: