Java Reference
In-Depth Information
But that's only part of what you need to do. To link this node into the list, you
have to reset front to point to this new node:
front = new ListNode(5, front);
Executing this line of code generates the following list:
data
5
next
data
19
next
data
8
next
data
42
next
/
front
This is a special case for your add method that applies only when the index is 0 .
So your method to add at an index should begin like this:
public void add(int index, int value) {
if (index == 0) {
front = new ListNode(value, front);
} else {
...
}
}
If you aren't adding at the front of the list, then you have to use a temporary vari-
able to position yourself to the appropriate spot in the list. This is another case in
which you have to stop one step early. In the case of the get method, you wanted to
position a local variable to the node with the given index. Here you want to stop one
step before that index:
public void add(int index, int value) {
if (index == 0) {
front = new ListNode(value, front);
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
...
}
}
Notice that the for loop test uses index - 1 instead of index so that it stops one
step early. For example, suppose that you had the same starting list of [19, 8, 42] and
Search WWH ::




Custom Search