|
|
|
|
|
|
|
Why bother returning the address if it is not used? Insert is declared in the base class, Node. The return value is needed by the other implementations. If you change the return value of HeadNode::Insert(), you will get a compiler error; it is simpler just to return the HeadNode and let the linked list throw its address on the floor. |
|
|
|
|
|
|
|
|
So what happened? The data was inserted into the list. The list passed it to the head. The head blindly passed the data to whatever the head happened to be pointing to. In this (first) case the head was pointing to the tail. The tail immediately created a new internal node, initializing the new node to point to the tail. The tail then returned the address of the new node to the head, which reassigned its myNext pointer to point to the new node. Hey! Presto! The data is in the list in the right place, as illustrated in Figure 19.3. |
|
|
|
|
|
|
|
|
FIGURE 19.3
The linked list after the first node is inserted. |
|
|
|
|
|
|
|
|
After inserting the first node, program control resumes at line 212. Once again the value is evaluated. For illustration purposes, assume that the value 3 is entered. This causes a new Data object to be created on line 216 and to be inserted into the list on line 217. |
|
|
|
|
|
|
|
|
Once again, on line 198 the list passes the data to its HeadNode. The HeadNode::Insert() method in turn passes the new value to whatever its myNext happens to be pointing to. As you know, it is now pointing to the node that contains the Data object whose value is 15. This invokes the InternalNode::Insert() method on line 97. |
|
|
|
|
|
|
|
|
On line 101, the InternalNode uses its myData pointer to tell its Data object (the one whose value is 15) to call its Compare() method, passing in the new Data object (whose value is 3). This invokes the Compare() method shown on line 42. |
|
|
|
|
|
|
|
|
The two values are compared; and, because myValue will be 15 and theOtherData.myValue will be 3, the returned value will be kIsLarger. This will cause program flow to jump to line 110. |
|
|
|
|
|