Java Reference
In-Depth Information
top
prev
np
15
23
36
52
30
1st
2nd
3rd
4th
5th
Figure 3-3.
After insertion of new node
Does this code work if
prev
were pointing at the last node so that we are, in fact, inserting after the last node? Yes.
If
prev
is the last node, then
prev.next
is
null
. Therefore, the following statement sets
np.next
to
null
so that the
new node becomes the last node:
np.next = prev.next;
As before,
prev.next
is set to point to the new node. This is illustrated by changing this:
np
top
69
prev
15
23
36
52
1st
2nd
4th
3rd
to this:
top
prev
np
15
23
36
52
69
1st
2nd
3rd
4th
5th
In many situations, it is required to insert a new node at the head of the list. That is, we want to make the new
node the first node. Assuming that
np
points to the new node, we want to convert this:
np
top
12
15
23
36
52
1st
2nd
3rd
4th
to this:
top
np
12
15
23
36
52
1st
2nd
3rd
4th
5th
This can be done with the following code:
np.next = top;
top = np;
The first statement sets the new node to point to whatever
top
is pointing at (that is, the first node), and the
second statement updates
top
to point to the new node.
Search WWH ::
Custom Search