Any algorithm that needs to work with elements other than the first one in our simple linked list will need to work its way through the list by following the next pointers from one node to the next.
For example, to print all the values in the list, we can start at the head node and repeatedly follow the next pointer to get to the next node, printing each nodeβs value. To keep track of where we are in the list, we can use a temporary pointer that starts at the head and moves through the list.
Assuming we call our pointer current, we can advance it to the next node by setting current = current->next;. That accesses the node that current points at, gets the memory address stored in its next member, and then updates the current pointer to point at that address.
You can click and drag on the animation area to pan around. Use the Ctrl + mouse wheel (or touchpad scroll gesture) while over the animation area to zoom in and out.
We never want to change the head pointer itself when traversing the list, because that would lose track of the listβs first node. Any loop logic will usually use a temporary pointer like the current in the animation to move through the list.
We donβt know in advance how many nodes are in the list, so we need a way to keep going until we reach the end. There are two conditions that we could use to determine when to stop:
Stop when the current pointer is nullptr, indicating we have moved past the last node.
Both approaches work, but the first one is often simpler because it allows us to handle the last node in the same way as all the others. It also allows us to handle the case of an empty list more easily, since the current pointer will be nullptr right from the start.
template <typename T>
void SimpleLinkedList<T>::print() const {
//current will point to each element in turn
ListNode<T>* current = head;
while(current != nullptr) {
cout << current->data << " "; //print current item
current = current->next; //advance to next
}
cout << endl;
}
Checkpoint27.6.1.
Why do we not delete current at the end of the print function?