Use new operator to construct a linked list of structures. - C++ Data Type

C++ examples for Data Type:struct

Description

Use new operator to construct a linked list of structures.

Demo Code

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int MAXRECS = 3;       // maximum number of records
struct Employee//w  w  w . j  av  a2  s.  co  m
{
   string name;
   string phoneNo;
   Employee *nextaddr;
};
void populate(Employee *);   // function prototype needed by main()
void display(Employee *);    // function prototype needed by main()
int main()
{
   int i;
   Employee *list, *current;  // two pointers to structures of
   // type Employee
   list = new Employee;
   current = list;
   for (i = 0; i < MAXRECS - 1; i++)
   {
      populate(current);
      current->nextaddr = new Employee;
      current = current->nextaddr;
   }
   populate(current);
   current->nextaddr = NULL;
   cout << "\nThe list consists of the following records:\n";
   display(list);
   return 0;
}
// Input a name and phone number
void populate(Employee *record)
{
   cout << "Enter a name: ";
   getline(cin,record->name);
   cout << "Enter the phone number: ";
   getline(cin,record->phoneNo);
   return;
}
void display(Employee *contents)
{
   while (contents != NULL)
   {
      cout << endl << setiosflags(ios::left) << setw(30) << contents->name << setw(20) << contents->phoneNo;
      contents = contents->nextaddr;
   }
   cout << endl;
   return;
}

Result


Related Tutorials