Search code examples
javadata-structureslinked-listnodessingly-linked-list

How does removing one link delete a node from a linked list?


I was reading through the code in the Crashing the Coding Interview book and when they delete a node in page 93, this is a snippet of the code they use:

Node deleteNode(Node head, int d){ 

while (n.next != null) {

if (n.next.data == d){
  n.next == n.next.next;
  return head;
  }

return head;
  }
}

What I don't understand is why this deletes the previous n.next node if the previous n.next node would still have a link to the node after it? I attached an illustration the help explain.

Thanks in advance!

enter image description here


Solution

    1. In languages/runtime supporting automatic garbage collection, the object referenced by this reference variable (b - unable to reach from any live thread of execution) will be garbage collected.
    2. Even in such cases, care should be taken to close any external resources properly (example - someone assigns a value stored in object referenced by b to their static reference).
    3. In runtimes without automatic garbage collection, it is the developer's responsibility to deallocate the resources.