Sample Programs For Linked List Class

These programs illustrate the use of the linked list class from the textbook with a struct stored at each node.  The previous set of notes shows how to copy the header file linklist.h from the instructor's account.


//  lldemo2.cxx
//  read info for a linked list from a file
//  and process it

#include <iostream.h> 
#include <iomanip.h> 
#include <fstream.h> 
#include <apstring.h> 

#include "linklist.h"


struct person
{
   apstring name;
   int age;
   double salary;
};

void main(void)
{
   LinkedList<person> list;

   person temp;

   ifstream fil;

   fil.open("something.dat");
   if( fil.fail() )
   {
      cout << "Big Trouble--File Is Missing";
      exit(1);
   }

   getline(fil,temp.name);
   while( !fil.eof() )
   {
      fil >> temp.age;
      fil >> temp.salary;
      fil.ignore();
      list.insert(temp);
//      list.next();
      getline(fil,temp.name);
   }

   list.first();

   while( !list.atEnd() )
   {
      temp = list.access();
      cout << temp.name << endl;
      cout << temp.age << endl;
      cout << temp.salary << endl;
      list.next();
   }


    apstring newname;
    cout << endl << endl << "Enter a Name to Look For ";
    getline( cin,newname );

   list.first();
   int found = 0;
   while( !list.atEnd() && !found )
   {
      temp = list.access();
      if( temp.name == newname )
        found = 1;
      else
        list.next();
   }

   if(found)
     cout << endl << "Age For " << newname << setw(10) << temp.age << endl;
   else
     cout << newname << " Not Found " << endl;

}

// lldemo3.cxx
// illustrates the modification of a linked list node
#include <iostream.h>
#include <apstring.h> 

#include "linklist.h"


struct person
{
   apstring name;
   int age;
   double salary;
};

void main(void)
{
   LinkedList<person> list;

   person one,two,three;
   person temp;

   one.name = "Sam";
   one.age = 24;
   one.salary = 22000;

   two.name = "Joan";
   two.age = 29;
   two.salary = 28000;

   three.name = "Matt";
   three.age = 35;
   three.salary = 43000;

   list.first();

   list.insert( three );
   list.insert( two );
   list.insert( one );

   list.first();

   while( !list.atEnd() )
   {
      temp = list.access();
      cout << temp.name << "   " << temp.salary << endl;
      list.next();
   }

   list.first();
   int found = 0;
   while( !list.atEnd() && !found )
   {
      temp = list.access();
      if( temp.name == "Joan" )
        found = 1;
      else
        list.next();
   }

   if(found)
{
  temp = list.access();
  temp.salary += 500;
  list.modify(temp);

//  the following is not allowed although it seems shorter
//  list.access().salary += 500;

  cout << "Raise Awarded" << endl << endl;

}
else
{

  cout << "Not Found" << endl;
}

   list.first();

   while( !list.atEnd() )
   {
      temp = list.access();
      cout << temp.name << "   " << temp.salary << endl;
      list.next();
   }


}