Java Reference
In-Depth Information
The value 4000 is then assigned to p ; in effect, p is pointing at the object just created. Since the actual address
4000 is not normally important, we usually depict this as follows:
p
next
num
36
In other words, p is pointing to the object wherever it happens to be.
When we read the first number, we must create a node for it and set top to point to the new node. In our example,
when we read 36 , we must create the following:
top
num
36
next
If n contains the new number, this can be accomplished with this:
if (top == null) top = new Node(n);
There are no arrows inside the computer, but the effect is achieved with the following (assuming the new node is
stored at location 4000 ):
top
4000
36
4000
For each subsequent number, we must set the next field of the current last node to point to the new node. The
new node becomes the last node. Suppose the new number is 15 . We must create this:
top
36
15
But how do we find the last node of the existing list? One method is to start at the top of the list and follow the
next pointers until we encounter null . This is time-consuming if we have to do it for each new number. A better
approach is to keep a pointer ( last , say) to the last node of the list. This pointer is updated as new nodes are added.
The code for this could be written like this:
np = new Node(n); //create a new node
if (top == null) top = np; //set top if first node
else last.next = np; //set last.next for other nodes
last = np; //update last to new node
Suppose there is just one node in the list; this is also the last node. In our example, the value of last will be 4000 .
Suppose the node containing 15 is stored at location 2000 . We have the following situation:
top
4000
last
2000
36
15
4000
4000
Search WWH ::




Custom Search