C++ linked list of objects

Description

C++ linked list of objects

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

using namespace std;

class NameLinkedList{
  public:/*from   ww w  .j  av  a 2  s.com*/
    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;
}



PreviousNext

Related