2016-10-03 81 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遍歷所有對象並檢查其他人指向它。如果不是,則標記爲刪除。