Java Reference
In-Depth Information
data
3
next
data
5
next
data
2
next
/
front
current
/
It's tempting to think that you could then execute the following line of code to
complete the task:
current = new ListNode(17);
But that won't work. It leaves the computer's memory looking like this:
data
3
next
data
5
next
data
2
next
/
front
data
17
next
/
current
The preceding code allocates a new node, but this new node has no connection to
the original list. The list is still composed of three nodes linked together. This fourth
node has been constructed, but it hasn't been properly linked into the list.
As you learn about linked list programming, you'll find that there are only two
ways to change the contents of a list:
change the value of front , in which case you are changing the starting point for
the list, or
change the value of <variable> .next (for some variable), which changes one of
the current links of the list.
To solve this problem, you have to stop one position early. You don't want to run
off the end of the list as you did with the print and toString code. Instead, you
want to position current to the final element. You can do this by changing your test.
Instead of running the loop until current becomes null , you want to run it until
current.next is null , because only the last node of the list will have a next field
that is null :
ListNode current = front;
while (current.next != null) {
current = current.next;
}
After the loop executes, current will be pointing at the last node in the list:
Search WWH ::




Custom Search