|
|
|
|
|
|
|
|
newNodePtr->component = inputVal; |
|
|
|
|  |
|
|
|
|
The current input value is stored into the component member of the newly created node. |
|
|
|
| |
|
|
|
|
currPtr->link = newNodePtr; |
|
|
|
|  |
|
|
|
|
The pointer to the new node is stored into the link member of the last node in the list. |
|
|
|
| |  |
|
|
|
|
currPtr is again pointing to the last node in the list. |
|
|
|
| |  |
|
|
|
|
The next input value (if there is one) is read in. The loop body repeats again. |
|
|
|
| |  |
|
|
|
|
The link member of the last node is assigned the special end-of-list value NULL. |
|
|
|
|
|
|
|
|
|
|
Following is the linked list that results when the program is run with the numbers 32, 78, 99, and 21 as data. The final values are shown for the auxiliary variables. |
|
|
|
|
|
|
|
|
Algorithms on Dynamic Linked Lists |
|
|
|
|
|
|
|
|
Now that we have looked at two examples of creating a dynamic linked list, let's look at algorithms that process nodes in a linked list. We need to be able to insert a node into a list, delete a node from a list, print the data values in a list, and so forth. For each of these operations, we make use of the fact that NULL is in the link member of the last node. NULL can be assigned to any pointer variable. It means that the pointer points to nothing. Its importance lies in the fact that we can compare the link member of each node to NULL to see when we have reached the end of the list. |
|
|
|
|
|
|
|
|
As we develop these algorithms, we do so in the following context. We want to write a C++ class for a list (not linked list) ADT. As emphasized in Figure 18-5, a list ADT can be implemented in several ways. We choose a dynamic linked list as the data representation for a list, and we create the OrdList class whose specification is shown in Figure 18-6. |
|
|
|
|
|