简体   繁体   English

从LinkedList的索引处删除元素

[英]Removal of an element from LinkedList at index

I'm looking to clarify something regarding removing elements from a LinkedList. 我想澄清一些有关从LinkedList中删除元素的信息。 Given this code: 给出以下代码:

public boolean remove(int index)
{
    // if the index is out of range, exit
    if(index < 1 || index > size())
        return false;

    Node current = head;
    for(int i = 1; i < index; i++)
    {
        if(current.getNext() == null)
            return false;

        current = current.getNext();
    }
    current.setNext(current.getNext().getNext());
    listCount--; 
    return true;
}

From what I can see, this code ends up at the element before the one you want to remove. 从我看到的内容来看,这段代码最终出现在要删除的元素之前。 It then assigns the 'next' field to the node after the one you want to remove. 然后,它将“下一个”字段分配给要删除的节点之后的节点。 My question is, do you not need to assign the 'next' field of the node you want to remove to null? 我的问题是,您是否不需要将要删除的节点的“ next”字段分配为null? I am a bit confused because it looks like the 'next' field still points to the element after, so you have 2 nodes pointing to it. 我有点困惑,因为看起来“下一个”字段仍然指向之后的元素,因此您有2个节点指向该元素。

Any help would be appreciated. 任何帮助,将不胜感激。

do you not need to assign the 'next' field of the node you want to remove to null? 您是否不需要将要删除的节点的“ next”字段分配为null?

There is no good reason to do this in Java. 没有充分的理由在Java中执行此操作。

I am a bit confused because 我有点困惑,因为

You must be thinking of how another language like C++ works, where you have to do this to clear a smart pointer as it uses reference counts. 您必须考虑另一种语言(如C ++)如何工作,必须在此清除智能指针,因为它使用引用计数。

In Java, a reference is just a 4-byte pointer (or index to an Object) 在Java中,引用只是4字节的指针(或对象的索引)

it looks like the 'next' field still points to the element after, so you have 2 nodes pointing to it. 看起来“下一个”字段仍然指向元素之后,因此您有2个节点指向该元素。

It's an object which has no references to it so it effectively doesn't exist. 这是一个没有引用的对象,因此实际上不存在。 All it does is waste a bit of memory until the garbage collector cleans it up. 它所做的只是浪费一点内存,直到垃圾收集器将其清除为止。

it looks like the 'next' field still points to the element after 看起来“下一个”字段仍然指向元素之后

It's not important, since nothing is pointing to the removed node it will be eventually automatically deleted by the garbage collector. 这并不重要,因为没有任何东西指向已删除的节点,所以最终它将由垃圾收集器自动删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM