Java中linkedList实现的remove方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20943233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove method for linkedList implementation in Java
提问by brain storm
I have this method from lecture on removing elements from linkedList
at specified index
.
I understand how the method works, but I do not understand why the for-loop
leaves the current node pointer
two index before the desired index.
我从关于从linkedList
at 中删除元素的讲座中得到了这种方法specified index
。我了解该方法的工作原理,但我不明白为什么在所需索引之前for-loop
留下current node pointer
两个索引。
Here is the method:
这是方法:
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;
}
}
The for-loop
goes from 0 to < index-1
, while I thought it should go from 0 to < index
. In this way, the pointer is at one index
before the index
that needed to be deleted. However, the above method works fine.
该for-loop
从0 to < index-1
,而我认为它应该从0 to < index
。这样,指针就在需要删除的指针index
之前index
。但是,上述方法工作正常。
For eg:
in the below LinkedList
例如:在下面 LinkedList
Lets consider removing Node C
. By the above loop-construct, current pointer
will be pointing at Node A
and current.next
will be Node B
. current.next.next
will be Node C
. Doing current.next=current.next.next
will result in Node B
deletion rather than Node C
.
让我们考虑删除Node C
. 通过上面的循环结构,current pointer
将指向Node A
和current.next
将是Node B
。current.next.next
将Node C
。这样做current.next=current.next.next
将导致Node B
删除而不是Node C
.
I think something is wrong with my understanding, can somebody explain?
我觉得我的理解有问题,有人可以解释一下吗?
采纳答案by Sotirios Delimanolis
The for-loop goes from 0 to < index-1
for 循环从 0 到 < index-1
In your example, removing C
means index is 2
. So i
only goes to 0
, since 1
is not < 1
.
在您的示例中,删除C
意味着 index is 2
。所以i
只能去0
,既然1
不是< 1
。
current
starts at A
, the for
loops once and current
goes to B
.
current
从 开始A
,for
循环一次并current
转到B
。
current
is B
, so current.next.next
is D
, which effectively removes C
.
current
是B
,所以current.next.next
是D
,这有效地消除了C
.