For illustration purposes, the class Datais created on lines 30–39, and the Compare()
method is implemented on lines 43–51. A Dataobject holds a value and can compare
itself with other Dataobjects. It also supports a Show()method to display the value of
the Dataobject.
The easiest way to understand the workings of the linked list is to step through an exam-
ple of using one. On line 203, a driver program is declared; on line 206, a pointer to a
Dataobject is declared; and on line 208, a local linked list is defined.
You can see the LinkListclass on lines 177–186. When the linked list is created, the
constructor on line 192 is called. The only work done in the constructor is to allocate a
HeadNodeobject and to assign that object’s address to the pointer held in the linked list
on line 185.
This allocation of a HeadNodeinvokes the HeadNodeconstructor shown on lines 163–166.
This, in turn, allocates a TailNodeand assigns its address to the head node’s myNext
pointer. The creation of the TailNodecalls the TailNodeconstructor shown on line 131,
which is inline and which does nothing.
Thus, by the simple act of allocating a linked list on the stack, the list is created, a head and
a tail node are created, and their relationship is established, as illustrated in Figure E.2.
882 Appendix E
FIGUREE.2
The linked list after it
is created.
Linked List
Head Node Tail Node
myHead myNext
Back in the driver program, line 212 begins an infinite loop. The user is prompted for
values to add to the linked list. He can add as many values as he likes, entering 0 when
he is finished. The code on line 216 evaluates the value entered; if it is 0 , it breaks out of
the loop.
If the value is not 0 , a new Dataobject is created on line 218, and that is inserted into the
list on line 219. For illustration purposes, assume the user enters the value 15. This
invokes the Insertmethod on line 198.
The linked listimmediately delegates responsibility for inserting the object to its head
node. This invokes the method Inserton line 170. The head node immediately passes
the responsibility to whatever node its myNextis pointing to. In this (first) case, it is
pointing to the tail node (remember, when the head node was born, it created a link to a
tail node). This, therefore, invokes the method Inserton line 142.
33 0672327112_app_e.qxd 11/19/04 12:30 PM Page 882