Java Reference
In-Depth Information
values are separated by commas. If we translate each array operation into its linked
list equivalent, we end up with the following code:
public String toString() {
if (front == null) {
return "[]";
} else {
String result = "[" + front.data;
ListNode current = front.next;
while (current != null) {
result += ", " + current.data;
current = current.next;
}
result += "]";
return result;
}
}
Notice that in this code we initialize current to front.next because we handle
the data for the first node outside the loop.
Appending add
Next let's consider how to write a method that will append a value to the end of the
list. To do so, we have to locate the end of the list. Let's think about the general case
in which we are appending a value to the end of a list that already contains a few
values. For example, suppose the list stores [3, 5, 2]:
data
3
next
data
5
next
data
2
next
/
front
Suppose that you want to add the value 17 at the end of the list. First you have to
get to the correct location. So here's a start:
ListNode current = front;
while (current != null) {
current = current.next;
}
What happens when this code executes is that the variable current moves along
the list from the first to the last node until the loop test fails—that is, until current
becomes null . The computer's memory then looks like this:
 
Search WWH ::




Custom Search