Create a linked list that links new objects to the end of the list - C++ Data Structure

C++ examples for Data Structure:Linked List

Description

Create a linked list that links new objects to the end of the list

Demo Code

#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>
#define nullptr 0  // required for pre-'09 compilers

using namespace std;

class NameLinkedList{
  public://from www .j ava  2 s .  c  o m
    string sName;
    NameLinkedList* pNext;
};

NameLinkedList* pHead = nullptr;

void add(NameLinkedList* pNDS){
    pNDS->pNext = nullptr;

    if (!pHead){
        pHead = pNDS;
        return;
    }
    NameLinkedList* pIter = pHead;
    while(pIter->pNext){
        pIter = pIter->pNext;
    }
    pIter->pNext = pNDS;
}
NameLinkedList* getData(){
    string name;
    cout << "Enter name:";
    cin  >> name;

    if (name == "exit"){
        return nullptr;
    }
    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;

    NameLinkedList* pNDS;

    while (pNDS = getData()){
        add(pNDS);
    }

    cout << "\nEntries:" << endl;
    for(NameLinkedList *pIter = pHead; pIter; pIter = pIter->pNext){
        cout << pIter->sName << endl;
    }
    return 0;
}

Result


Related Tutorials