|
|
|
|
|
|
|
To print the components of a linked list, we need to access the nodes one at a time. This requirement implies an eventcontrolled loop where the event that stops the loop is reaching the end of the list. The loop control variable is a pointer that is initialized to the external pointer and is advanced from node to node by setting it equal to the link member of the current node. When the loop control pointer equals NULL, the last node has been accessed. |
|
|
|
|
|
|
|
|
Set currPtr = head
WHILE currPtr doesn't equal NULL
Print component member of *currPtr
Set currPtr = link member of *currPtr |
|
|
|
|
|
|
|
|
|
Note that this algorithm works correctly even if the list is empty (head equals NULL). |
|
|
|
|
|
|
|
|
void OrdList::Print() const
// Postcondition:
// component members of all nodes (if any) in linked list
// have been output
{
NodePtr currPtr = head; // Loop control pointer
while (currPtr != NULL)
{
// Invariant (prior to test):
// component members of all nodes before *currPtr
// have been output
// && currPtr points to a list node or == NULL
cout < currPtr->component < ' ';
currPtr = currPtr->link;
}
} |
|
|
|
|
|
|
|
|
Let's do a code walk-through using the following list. |
|
|
|
|
|