Create a linked list to store name - C++ Data Structure

C++ examples for Data Structure:Linked List

Description

Create a linked list to store name

Demo Code

#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class NameLinkedList{
  public:/*from  ww  w.j av a  2s  .  c om*/
    NameLinkedList(string& refName): sName(refName), pNext(0) {}
    void add()
    {
        this->pNext = pHead;
        pHead = this;
    }
    // access methods
    static NameLinkedList* first() { return pHead; }
           NameLinkedList* next()  { return pNext; }
          const string& name()  { return sName; }
  protected:
    string sName;

    // the link to the first and next member of list
    static NameLinkedList* pHead;
    NameLinkedList* pNext;
};

// allocate space for the head pointer
NameLinkedList* NameLinkedList::pHead = 0;

NameLinkedList* getData(){

    string name;
    cout << "Enter name:";
    cin  >> name;

    if (name == "exit"){
        return 0;
    }
    return new NameLinkedList(name);
}

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

    NameLinkedList* pNDS;
    while (pNDS = getData())
    {
        pNDS->add();
    }

    cout << "\nEntries:" << endl;
    for(NameLinkedList *pIter = NameLinkedList::first();pIter;pIter = pIter->next())
    {
        cout << pIter->name() << endl;
    }
    return 0;
}

Result


Related Tutorials