donnemartin / interactive-coding-challenges

120+ interactive Python coding interview challenges (algorithms and data structures). Includes Anki flashcards.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Remove reference to deleted node

rafadaguiar opened this issue · comments

In the stack challenge (stacks_queues/stack/stack_challenge), more specifically in the pop() method, shouldn't we be removing references from the node we want to pop? Only updating the top reference doesn't remove the reference the old top (popped item) has to the new top.

Hi Rafael,

Only updating the top reference doesn't remove the reference the old top (popped item) has to the new top

Can you point me to a link that discusses this further?

For reference, I believe this is the function we are discussing:

    def pop(self):
        if self.top is not None:
            data = self.top.data
            self.top = self.top.next
            return data
        return None

It is my understanding that:

  • Python's garbage collector will automatically handle this without the need to "remove references from the node we want to pop".
  • If this were C/C++ and that node were created with malloc/new then we should deallocate that memory.

-Donne

Hi Donne, I misunderstood the way Python gc works. I was thinking that any reference pointing in or out the object would keep it alive, but it's not the case (only references to the object work for that matter).

Sounds good, thanks Rafael :)