Java Reference
In-Depth Information
As a result of these steps, the new desk references the current first desk in the chain and becomes
the new first desk.
Here are the analogous steps that add takes:
newNode references a new instance of Node
Place data in newNode
Set newNode 's link to firstNode
Set firstNode to newNode
That is, we make the new node reference the first node in the chain, making it the new first node.
Figure 3-7 illustrates these steps, and the following Java statements implement them:
Node newNode = new Node(newEntry);
newNode.next = firstNode;
firstNode = newNode;
FIGURE 3-7
A chain of nodes (a) just prior to adding a node at the begin-
ning; (b) just after adding a node at the beginning
(a)
(b)
firstNode
firstNode
newNode
newNode
Adding a node to an empty chain, as Figure 3-6 depicts, is actually the same as adding a node
to the beginning of a chain. Question 3 asks you to think about this fact.
Question 3 The code that we developed in Segment 3.10 to add a node to an empty chain is
Node newNode = new Node(newEntry);
firstNode = newNode;
The code that we just developed to add to the beginning of a chain is
Node newNode = new Node(newEntry);
newNode.next = firstNode;
firstNode = newNode;
Why do these three statements also work correctly when the chain is empty?
3.12
The method add . As you have seen, although it might appear that an empty bag is a special case
when adding a new entry to a bag, it really is not. The following definition of the method add uses
this conclusion:
/** Adds a new entry to this bag.
@param newEntry the object to be added as a new entry
@return true */
public boolean add(T newEntry) // OutOfMemoryError possible
 
Search WWH ::




Custom Search