Need help understanding linked lists

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;
	}

}
Last edited on
> 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.


By the way, you ought to delete what you new
Yes when I use new I use delete this is an example from a book.
Topic archived. No new replies allowed.