Linked Lists

Can someone explain how this works? I'm learning from a book but it either doesn't do a good job explaining or I can't grasp the concept.

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
//Link.h

class Link
{
public:
	string sName;
	Link* pNext;
};

Link* pHead = nullptr;

void add(Link* pLC)
{
	pLC->pNext = pHead;

	pHead = pLC;
}

Link* getData()
{
	string name;

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

	if(name == "Exit")
	{
		return 0;
	}

	Link* pLC = new Link;
	pLC->sName = name;
	pLC->pNext = 0;

	return pLC;
}

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
//main.cpp

#include <iostream>
#include <string>

using namespace std;

#include "Link.h"

int main()
{
	Link* pLC;

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

	cout << "\nEntries: " << endl;

	for(Link *pOW = pHead; pOW; pOW = pOW->pNext)  
	{
		cout << pOW->sName << endl;
	}
	
	return 0;
}


Most of my confusion comes from the pNext. No idea how that is working. Help would be appreciated.
pNext is a pointer. In this case pNext is either 0, or knows where the next item of the list is. pNext is the directional link between items of the linked list.
Yes, but how does it know. I don't see how it is ever above 0. This line:

Link* pHead = nullptr

sets it 0 every time it goes into add(). Am I misreading it?
Only the first time. Same add changes pHead.

Bad style IMO. pHead is a global variable and holds the one and only list of the program.
Thank you.
Topic archived. No new replies allowed.