java - 删除单链表中间的节点

标签 java linked-list garbage-collection

我编写了一个程序,可以删除给定节点的单个链表中的节点。

public class Solution {
    /**
     * @param node: the node in the list should be deleted
     * @return: nothing
     */
    public void deleteNode(ListNode node) {
        // write your code here
        // if node.next==null, we cannot delete the current node without given the previous node
        if(node == null || node.next == null) return;
        ListNode next = node.next;
        node.val = next.val;
        node.next = next.next;
        // I wonder if this link needs to be removed as well
        next.next = null;        
    }
}

问题很简单。然而,网上的许多代码示例不包含我写的这一行:

        next.next = null;        

如果没有这一行,我们就已经删除了该节点。之后,虽然没有任何东西指向“next”,但“next”仍然指向next.next。如果不设置next.next = null,Java垃圾收集器会删除这个已删除的节点吗?

最佳答案

确实会的。 gc 会遍历所有对象并检查是否有其他对象指向它。如果没有,则将其标记为删除。

关于java - 删除单链表中间的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39835858/

相关文章:

java - 如何向 < 添加对象?扩展接口(interface)>?

java - 直接调用 String 方法是否也会将该 String 存储在 String 池中?

garbage-collection - 如何打破垃圾收集?

Java/实现链表

java - 如何更改垃圾收集线程的优先级?

vb.net - 如何正确退出应用程序

java - 更改长变量的格式?

java.lang.Object;无法转换为模型类 : error in Spring Boot

java - LinkedList 类中的 element() 和 getFirst() 方法有什么区别?

java - 为什么需要(LinkedList)?