A Node
has to main members:
1 - A pointer to another node. (ptr
, in your example)
2 - The data value it holds. (data
, in your example)
Head
stands for the first node in the list.
So,
Node<T> *ptr = Head; // ptr points the ftrst node in the list.
while (ptr) // the last node points nowhere (NULL), so if ptr is NULL we hit the end of the list.
{
T n = ptr -> data; // This no need explanation.
ptr = ptr -> next; // now we want to ptr point to the node is pointing its `next` pointer.
}
This is how the pointer ptr
advances through the list:

Further questions
Why do we have to derefence the pointer to access the next pointer or even the data itself?
You don't have to.
ptr->data; // data is a member in a struct/class POINTED by ptr.
*ptr; // this is the class/struct INSTANCE (dereferenced). So
*ptr.data; // data is a member of that instance.
If you have:
Node a;
Node *ptr = &a;
// Following are the same:
a.next;
ptr->next;
*ptr.next;
Also since ptr
is will point at data, and you dereference that to get the actual value of the data. is that correct?
No, ptr
never will be pointed to data (according the example code).
ptr->data; // This not means ptr will POINT to data.
// this means "access to the data member of whatever object being POINTED by ptr".
Based on the code given, ptr will actually point at every single member in the linked list?
Yes, you got it!!
How does ptr->next
get evaluated to the address of the next node?
A pointer is also a variable. An int
variable hold int
values, a pointer hold addresses.
A very simple (and useless) Node
would be something like this:
struct Node {
Node *next; // Pointer to another node, yeah but ... which node? In a minute ;)
};
at some point you will have to write code like this:
// Example of adding a node.
Node* Head = new Node;
Node* another_node = new Node;
Head->next = another_node; // This is how Head->next "knows" which node is the next. Because we told him.
So, now if we point at the same address of Head with another pointer, lets say ptr
...
Node *ptr = Head;
Then we have access to Head
's next member through ptr->next
. And ofcourse this evaluates to the address of another_node
.