Store data in a linked list of objects - C++ Class

C++ examples for Class:object

Description

Store data in a linked list of objects

Demo Code

#include <cstdio>
#include <string>
#include <cstdlib>
#include <iostream>

using namespace std;

class NameLinkedList {
public:/* w  w w  .ja v a2 s .  co m*/
  string sName;

  // the link to the next entry in the list
  NameLinkedList* pNext;
};

// the pointer to the first entry in the list
NameLinkedList* pHead = nullptr;

// add - add a new member to the linked list
void add(NameLinkedList* pNDS)
{
  // point the current entry to the beginning of list
  pNDS->pNext = pHead;

  // point the head pointer to the current entry
  pHead = pNDS;
}

NameLinkedList* getData()
{
  string name;
  cout << "Enter name:";
  cin >> name;

  // if the name entered is 'exit'...
  if (name == "exit")
  {
    // ...return a null to terminate input
    return nullptr;
  }

  // get a new entry and fill in values
  NameLinkedList* pNDS = new NameLinkedList;
  pNDS->sName = name;
  pNDS->pNext = nullptr; // zero link

  return pNDS;
}

int main(int nNumberofArgs, char* pszArgs[])
{
  cout << "Read names of employees\n" << "Enter 'exit' for first name to exit" << endl;

  // create (another) NameLinkedList object
  NameLinkedList* pNDS;

  while (pNDS = getData()) {
    // add it to the list of NameLinkedList objects
    add(pNDS);
  }

  cout << "\nEntries:" << endl;

  for (NameLinkedList *pIter = pHead; pIter; pIter = pIter->pNext) {
    cout << pIter->sName << endl;
  }

  return 0;
}

Result


Related Tutorials