Java Reference
In-Depth Information
This code still doesn't work. The test for current.next being null should
stop changing current at the right place, but when current.next is null , it is
not legal to ask for the value of current.next.data . That test will throw a
NullPointerException . This test is an example of a combination of a sensitive and
robust test:
while (current.next.data < value && current.next != null)
sensitive test
robust test
You need to switch the order of these tests to make them work properly.
while (current.next != null && current.next.data < value)
Recall from Chapter 5 that Java uses what is known as short-circuited evaluation,
which means that if the first test evaluates to false , Java doesn't bother to perform
the second test. So the first test, in effect, protects you from the potential problem
generated by the second test (the NullPointerException ).
Incorporating these changes, you end up with the following code:
ListNode current = front;
while (current.next != null && current.next.data < value) {
current = current.next;
}
current.next = new ListNode(value, current.next);
But even this code is not enough. The first test in this loop is the robust test, but it
isn't very robust. If current is null , then it throws a NullPointerException . So
you want to execute this code only in the case in which front isn't null .
There is another special case. If the value to be inserted belongs at the very front
of the list, then this code will place it in the wrong spot. It always inserts after a node
currently in the list, never in front of all nodes.
For example, suppose that you want to insert the value 1 in the previous list that
begins with the value 2 . The code that you have written starts current at the front of
the list and inserts the value after that node by changing the value of current.next .
So the value 1 would be inserted after the value 2 , which is clearly wrong.
For the “front of the list” case, you have to write code that changes front rather
than changing current.next . In what case would you want to do that? When the
value is less than front.data . And what exactly do you want to do? You want to set
front to a new list node that points at the old front of the list:
if (value < front.data) {
front = new ListNode(value, front);
}
Search WWH ::




Custom Search