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 linkedListat specified index.
I understand how the method works, but I do not understand why the for-loopleaves the current node pointertwo index before the desired index.
我从关于从linkedListat 中删除元素的讲座中得到了这种方法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-loopgoes from 0 to < index-1, while I thought it should go from 0 to < index. In this way, the pointer is at one indexbefore the indexthat 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 pointerwill be pointing at Node Aand current.nextwill be Node B. current.next.nextwill be Node C. Doing current.next=current.next.nextwill result in Node Bdeletion 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 Cmeans index is 2. So ionly goes to 0, since 1is not < 1.
在您的示例中,删除C意味着 index is 2。所以i只能去0,既然1不是< 1。
currentstarts at A, the forloops once and currentgoes to B.
current从 开始A,for循环一次并current转到B。
currentis B, so current.next.nextis D, which effectively removes C.
current是B,所以current.next.next是D,这有效地消除了C.

