![]() When you're asked to delete a node from a given single linked list. Here's my thought process:
This code snippet below demonstrates a quick way of removing a middle node from a single linked list: public class LinkedList{ #1) Define the contract for the function I'd assume I have a LinkedList class, I want to have a function that, given a node, remove/delete the given node from the linked list it belongs to and return a boolean to indicate success or failure. public boolean deleteNode(LinedListNode n) #2) Check on boundary conditions The first boundary condition to check is whether the passed-in node n is null. If so, there's nothing to delete, and you may consider the delete-a-node operation is successful or failed at your discretion. The second boundary condition to check is if the given node to be deleted is the last node, that is, n.next == null. As such, the #1 approach won't work but to code extra to deal with this scenario. #3) Code for the generic case To quickly remove a node from the linked list, modify the given node to hold data of its next node, then return either true or false of the removal operation. The GC will remove the orphaned next node of the given node eventually.
0 Comments
Leave a Reply. |
Categories
All
Archives
May 2020
|