Java Reference
In-Depth Information
current = current.next;
}
...
}
}
If you are working with the list [19, 8, 42, 13] and you are removing the value
from index 2, your list will look like the following:
next
next
next
/
next
/
data
19
data
8
data
42
data
13
front
current
To remove the value from index 2, you need to change current.next to point to
the value that comes next, which is stored in current.next.next :
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
}
Now the linked list looks like this:
data
19
next
data
8
next
data
42
next
/
data
13
next
/
front
current
The code has properly linked around the node that stores the value 42 (which is
the value that was stored at index 2), so the list now stores the sequence of values
[19, 8, 13].
As you write methods that involve manipulating values in the middle of the list, it
becomes clear that you often end up writing the same kind of loop to position to a
particular node in the list. This is a great place to introduce a private method:
private ListNode nodeAt(int index) {
ListNode current = front;
Search WWH ::




Custom Search