< previous page page_1057 next page >

Page 1057
NodePtr       head;            // External pointer to list
NodePtr       newNodePtr;      // Pointer to newest node
NodePtr       currPtr;         // Pointer to last node
ComponentType inputVal;

head = new NodeType;
cin >> head->component;
currPtr = head;

cin >> inputVal;
while (cin)
{
        // Invariant (prior to test):
        //     All previous values of inputVal have been placed
        //     into linked list pointed to by head
        //  && currPtr points to last node in list

    newNodePtr = new NodeType;         // Create new node
    newNodePtr->component = inputVal;  // Set its component value
    currPtr->link = newNodePtr;        // Link node into list
    currPtr = newNodePtr;              // Set currPtr to last node
    cin >> inputVal;
}
currPtr->link = NULL;                  // Mark end of list
Let's do a code walk-through and see just how this algorithm works.
head = new NodeType;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
A variable of type NodeType is created. The pointer is stored into head. Variable head will remain unchanged as the pointer to the first node (that is, head is the external pointer to the list).
cin >> head->component;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The first number is read into the component member of the first node in the list.
currPtr = head;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
currPtr now points to the last node (the only node) in the list.
cin >> inputVal;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The next number (if there is one) is read into variable inputVal.
while (cin)
{
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
An event-controlled loop is used to read input values until end-of-file occurs.
newNodePtr = new NodeType;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Another variable of type NodeType is created, with newNodePtr pointing to it.

 
< previous page page_1057 next page >