Java Reference
In-Depth Information
The method
outputList
continues to move the
position
variable down the linked
list and outputs the data in each node as it goes along. When
position
reaches the last
node, it outputs the data in that node and then again executes
position = position.getLink( );
If you study Display 15.4, you will see that when
position
leaves the last node, its
value is set to
null
. At that point, we want to stop the loop, so we iterate the loop
while
(position !=
null
)
A similar technique is used to traverse the linked list in the methods
size
and
find
.
Next let's consider how the method
addToStart
adds a node to the start of the
linked list so that the new node becomes the first node in the list. It does this with the
single statement
adding a
node
head =
new
Node1(itemName, itemCount, head);
The new node is created with
new
Node1(itemName, itemCount, head)
which returns a reference to this new node. The assignment statement sets the variable
head
equal to a reference to this new node, making the new node the first node in the
linked list. To link this new node to the rest of the list, we need only set the
link
instance variable of the new node equal to a reference to the
old first node
. But we have
already done that:
head
used to point to the old first node, so if we use the name
head
on
the right-hand side of the assignment operator
,
head
will denote a reference to the old
first node. Therefore, the new node produced by
new
Node1(itemName, itemCount, head)
points to the old first node, which is just what we wanted. This is illustrated in Dis-
play 15.5.
Later, we will discuss adding nodes at other places in a linked list, but the easiest
place to add a node is at the start of the list. Similarly, the easiest place to delete a node
is at the start of the linked list.
The method
deleteHeadNode
removes the first node from the linked list and leaves the
head
variable pointing to (that is, containing a reference to) the old second node (which is
now the first node) in the linked list. This is done with the following assignment:
removing a
node
head = head.getLink( );