1 回答
TA贡献1891条经验 获得超3个赞
返回void
使用两个索引
private void remove(int index, int current, Node n) {
if (n == null || index <= 0 || (index == 1 && n.next == null) {
throw new IndexOutOfBoundsException();
}
if (current == index - 1) {
// Remove 'n.next'.
n.next = n.next.next;
} else {
remove(index, current + 1, n.next);
}
}
用法
public void remove(int index) {
if (first == null || index < 0) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
// Remove 'first'.
first = first.next;
} else {
remove(index, 0, first);
}
size--;
}
使用一个索引
只需要一个索引:
private void remove(int index, Node n) {
if (n == null || index <= 0 || (index == 1 && n.next == null) {
throw new IndexOutOfBoundsException();
}
if (index == 1) {
// Remove 'n.next'.
n.next = n.next.next;
} else {
remove(index - 1, n.next);
}
}
用法
public void remove(int index) {
if (first == null || index < 0) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
// Remove 'first'.
first = first.next;
} else {
remove(index, first);
}
size--;
}
返回Node
更好的是返回而不是:Nodevoid
private Node remove(int index, Node n) {
if (n == null || index < 0) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
// Remove 'n' and return the rest of the list.
return n.next;
}
// 'n' stays. Update the rest of the list and return it.
n.next = remove(index - 1, n.next);
return n;
}
用法
public void remove(int index) {
first = remove(index, first);
size--;
}
添加回答
举报