< previous page page_1056 next page >

Page 1056
We would like to generalize this algorithm so that we can use a loop to create a dynamic linked list of any length. In the algorithm, we used three pointers:
1. head, which was used in creating the first node in the list and became the external pointer to the list.
2. newNodePtr, which was used in creating a new node when it was needed.
3. currPtr, which was updated to always point to the last node in the linked list.
When building any dynamic linked list by adding each new node to the end of the list, we always need three pointers to perform these functions. The algorithm that we used is generalized below to build a linked list of int numbers read from the standard input device. It is assumed that the user types in at least one number.
Set head = new NodeType
Read head->component
Set currPtr = head

Read inputVal
WHILE NOT EOF
  Set newNodePtr = new NodeType
  Set newNodePtr->component = inputVal
  Set currPtr->link = newNodePtr
  Set currPtr = newNodePtr
  Read inputVal
Set currPtr->link = NULL

The following code segment implements this algorithm. Notice how the first Typedef statement defines the component type to be int rather than float.
typedef int ComponentType;

struct NodeType;               // Forward declaration
typedef NodeType* NodePtr;

struct NodeType
{
    ComponentType component;
    NodePtr       link;
};

 
< previous page page_1056 next page >