I'm having trouble understanding linked lists. I understand they are generally LIKE arrays, in that they are a list of data objects linked together by pointers. So the pointer to the next node goes inside of the class (or struct) and is itself an object of that very same class? Also can you explain the need for the use of the new keyword in this code, allocating off the heap.
It also appears my learning resource uses a global variable to define the pointer to pHead. Is this necessary?
Any other useful tips or bits of information to help me understand the use of pointers and objects in this code would be helpful as well.
class NameDataSet
{
public:
string sName;
// Link to next entry in the list
NameDataSet* pNext;
};
// The pointer to the first entry in the list
NameDataSet* pHead = 0;
// Add a new member to the linked list
void add (NameDataSet* pNDS)
{
// Point the current entry to the beginning of the list
pNDS->pNext = pHead;
// point the head pointer to the current entry
pHead = pNDS;
}
NameDataSet* getData()
{
// read first name
string name;
cout << "\nEnter name::";
cin >> name;
// if the name entered is 'exit'....
if (name == "exit")
{
//return null to terminate input
return 0;
}
// get a new entry and fill in values
NameDataSet* pNDS = new NameDataSet;
pNDS->sName = name;
pNDS->pNext = 0; // zero link
// return the address of the object created
return pNDS;
}
int main(int nNumberofArgs, char* pszArgs[])
{
cout << "Read names of students\n"
<< "Enter 'exit' for first name to exit"
<< endl;
// create another NameDataSet object
NameDataSet* pNDS;
while (pNDS = getData())
{
// Add it to the list of NameDataSet Objects
add(pNDS);
}
// display the objects
for (NameDataSet *pIter = pHead; pIter; pIter = pIter->pNext)
{
cout << pIter->sName << endl;
}
}
> I understand they are generally LIKE arrays, in that they are a list of data objects linked together by pointers.
Excuse my English, but that does not sound `array like' at all.
> So the pointer to the next node goes inside of the class (or struct) and is itself an object of that very same class?
No, a pointer is a pointer.
> Also can you explain the need for the use of the new keyword in this code, allocating off the heap.
¿what alternative do you have?
> uses a global variable to define the pointer to pHead. Is this necessary?
It would be better to encapsulate in a `list' class, so you don't have to deal with nodes.