Java Reference
In-Depth Information
Some people prefer to write the code for creating the new node in two steps with a
temporary variable, as in the following lines of code:
// first construct the node
ListNode temp = new ListNode(5, current.next);
// then link it into the list
current.next = temp;
Both approaches work. After you have incorporated this code into your method,
the code looks like this:
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;
}
current.next = new ListNode(value, current.next);
}
}
You can use a similar approach to writing the remove method. You need to include
a special case for the front of the list, in which case you can simply leapfrog over the
first element:
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
...
}
}
For values that appear later in the list, you need a loop similar to the one that you used
in the add method to reach the position at the node just before the one to be removed:
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
Search WWH ::




Custom Search