how is non referenced node being garbage collected if it is referencing another node.

  • 1

    So with a solution like this:

    public void deleteNode(ListNode node) {;;

    And we have :

    before:  1->2->3->4

    Call delete node 3

    after:  1->2->4

    So using the solution above, we'll actually still have the 3 node existing with no reference to it (BUT the 3 node still has a reference to the 4 node in its next value).

    How exactly does this 3 node get collected by the garbage collector?  Since from my understanding it still contains a reference to the 4 node and would only be garbage collected if nothing referenced it and it didn't reference anything else.

  • 0

    Hmmmm... I just took for granted how it was being garbage collected, but you bring up a good point. I wonder how the garbage collector is working here....


  • 1

    The garbage collector only deletes an object if that object is not referenced directly or indirectly by any variables in the environment. If nothing references node 3 after setting, the garbage collector knows to delete it. It does not matter what an object itself references when the garbage collector decides whether to delete the object or not. If node 3 contains a reference to another node, it still isn't reachable by the program if it has no references pointing to it.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.