C++ linked list to store name

Description

C++ linked list to store name

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

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

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

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

MyList* getData(){

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

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

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

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

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



PreviousNext

Related