When removing a node, why isn't it necessary to set that node's next to null?

Shisui :

I've noticed that a lot of code online for the remove node or delete node function of a singly LinkedList merely set the previous node's next to the next of the node to be removed. But isn't that an incomplete deletion, because the deleted node is still pointing to it's next?

For example

A->B->C

If you delete B, you should make A point to C. But if you don't make B point to null, doesn't B still exist because it's pointing to C?

Like wise, for a doubly linkedList in java, if you were deleting a node wouldn't you need to make sure that the node is no longer pointing to anything for it to be truly deleted?

lealceldeiro :

if you don't make B point to null, doesn't B still exist because it's pointing to C?

No. The reason is that as there is not any reference towards B, it will be garbaged collected. It doesn't matter if it (B) is still pointing to something.

Like wise, for a doubly linkedList in java, if you were deleting a node wouldn't you need to make sure that the node is no longer pointing to anything for it to be truly deleted?

The principle is the same. What changes is that you need to change two references: the previous node of the node being deleted (making it point to the next of the node being deleted) and the next of the node being deleted (making it point to the previous of the node being deleted).

When there are no references to the node being deleted, this will be garbaged collected.

In general, when there isn't a reference pointing to some object, this will be garbaged collected at some point.


Here is a very similar post that may be useful to you: Garbage collector in java - set an object null

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325630&siteId=1