【发布时间】:2014-01-06 04:56:58
【问题描述】:
我在specified index 的关于从linkedList 中删除元素的讲座中获得了这种方法。
我了解该方法的工作原理,但我不明白为什么 for-loop 在所需索引之前留下了 current node pointer 两个索引。
方法如下:
public void remove(int index) {
if (index == 0) {
// removing the first element must be handled specially
front = front.next;
} else {
// removing some element further down in the list;
// traverse to the node before the one we want to remove
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
// change its next pointer to skip past the offending node
current.next = current.next.next;
}
}
for-loop 来自0 to < index-1,而我认为它应该来自0 to < index。这样,指针就位于需要删除的index 前一个index。但是,上述方法效果很好。
例如:
在下面LinkedList
让我们考虑删除Node C。通过上述循环构造,current pointer 将指向Node A,current.next 将指向Node B。 current.next.next 将是 Node C。执行current.next=current.next.next 将导致Node B 删除而不是Node C。
我觉得我的理解有问题,谁能解释一下?
【问题讨论】:
标签: java pointers methods linked-list