Java Reference
In-Depth Information
Just calling the constructor leaves the computer's memory looking like this:
data
10
next
data
2
next
data
5
next
data
12
next
/
front
current
But now you have to link this into the list by changing
current.next
:
current.next = new ListNode(value, current.next);
Now the computer's memory looks like this:
data
10
next
data
2
next
data
5
next
data
12
next
/
front
current
This diagram isn't the easiest picture to read, but if you follow the links carefully,
you'll see that, starting at the front, the sequence of values is 2, 5, 10, 12, which is
what you want.
The code works for most cases, but it is incomplete. What if you want to insert the
value
42
? Remember your loop test:
while (current.next.data < value)
This code depends on finding a value in the list that is less than the value you are
trying to insert. What if there is no such value, as in the case of
42
? This code keeps
moving
current
forward until
current.next
is
null
. At that point, when you try
to ask for the value of
current.next.data
, you are asking for
null.data
, which
throws a
NullPointerException
because Java is looking for the
data
field of a
nonexistent object.
If the value that you wish to insert is greater than everything else in the list, then it
belongs after the last node in the list. So you want to stop when
current
gets to the
last node in the list. Thus, a second (still incorrect) attempt at writing the code for the
test would be
while (current.next.data < value && current.next != null)
Search WWH ::
Custom Search