简体   繁体   中英

Doubly Linked List delete last

I have a reference to the head and lastNode. Hi I have a question. When I delete the last node in a doubly linked list do I have to set the previous reference of the node to null or can I just leave it. I do something like this when deleting the lastNode.

lastNode = lastNode.prev; // lets lastNode reference the new last node
lastNode.next = null; // removes link to the old last node

When I do the toString method it prints as expected. Just wondering if its necessary to set the old last node prev to null or not. Or will the garbage collector just delete it since theres no reference to it even though the old node still has a reference to a node in the linked list

You would only need to update the reference to null if there was any way to access the newly deleted lastNode object. If there is no way to reach this node by traversing the list, then you shouldn't have to worry about it.

Although, It is good practice to do this sort of cleanup just in case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM