Java Reference
In-Depth Information
Question 1
Describe the steps that the method
getNodeAt
must take to locate the node at
a given position.
14.4
Case 4: Adding a node to the end of a chain.
To add a node to the end of an existing chain, we
can take the following steps:
newNode
references a new instance of
Node
Place
newEntry
in
newNode
Locate the last node in the chain
Place the address of
newNode
in this last node
That is, we make the last node in the chain reference the new node. Using the same
method,
getNodeAt
, that the previous segment described, we can implement these steps in
Java as follows:
Node newNode =
new
Node(newEntry);
Node lastNode = getNodeAt(numberOfNodes);
lastNode.setNextNode(newNode);
Figure 14-4 illustrates this addition to the end of a chain of nodes.
FIGURE 14-4
A chain of nodes (a) prior to adding a node at the end;
(b) after locating its last node;
(c) after adding a node at the end
(a)
firstNode
newNode
(b)
firstNode
lastNode
newNode
(c)
firstNode
lastNode
newNode
Note:
Adding a new node to the end of a chain of
n
nodes can be thought of as adding the
node at position
n
+ 1.