2016-10-03 76 views
1

我已经编写了一个程序,该程序删除给定节点的单个链接列表中的节点。删除单个链接列表中间的节点

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 = null,Java垃圾收集器是否会删除这个被删除的节点?

+0

要删除'node','next.next'是'node.next.next',它是实际的第三个节点。它不应该被删除。 – 11thdimension

回答

1

的确如此。 gc遍历所有对象并检查其他人指向它。如果不是,则标记为删除。