printing a linked list

Hello, I am learning linked list, and have come across something that I am having issues with. It is more related to pointers i guess, but the pointer is in use with a linked list node.

The code below has two similar print functions, just the while loop is different, and im wondering exactly why one works and the other doesnt when the list only has 1 element.

Does the one that uses simply tempNodeptr != null , refer to the pointer itself, so using tempNodePtr != null is true because the node pointer is pointing to a node. But tempNodePtr-> next , refers to the actual node, and tempNodePtr->next != null would be false, because that node does not have a node 'after' it?

Im not sure if my wording of this is a bit confusing, I could try word it a bit better if that would help



1
2
3
4
5
6
7
8
9
10
  print()
{
	Node* tempNodePtr = head;

	while (tempNodePtr != nullptr)
	{
		std::cout << tempNodePtr->data;
		tempNodePtr = tempNodePtr->next;;
	}
}



1
2
3
4
5
6
7
8
9
10
  print()
{
	Node* tempNodePtr = head;

	while (tempNodePtr->next != nullptr)
	{
		std::cout << tempNodePtr->data;
		tempNodePtr = tempNodePtr->next;;
	}
}
the second loop will dereference a null pointer if the list is empty, on line 5.
you can fix that with while(tempNodePtr && tempNodePtr->next)

but why bother, its a lot of extra words for nothing gained?

you can also do it with a for loop and its prettier IMHO:
for(Node* t = head; t; t=t->next)
cout << t->data;

and just to make sure you understand..
1 - > 2 -> 3 ->null
tmp is head, and points to 1.
print 1. tmp points to 2.
print 2, tmp points to 3
print 3, tmp points to null
tmp is null, stop.
tmp IS a node pointer. that is its TYPE. its VALUE can be null.
its like an integer... int i can be zero, or it can be not zero. its type is int, but its value may or may not be zero. null works the same way.
if you remember your earliest code, back when you did stuff like "enter -999 to stop" for your first loops, the sentinel value approach? Nullptr is a sentinel, the way it is used in this kind of code.
Last edited on
Topic archived. No new replies allowed.