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

Viewed 87

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

2 Answers
  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.

When we code with Java the Node that contain the b value will be removed by the garbage collector (GC) in the Java virtual machine (JVM). But with C language you should destroy this Node using free() function. this is an example of creation and destruction of one node in C (we assume that "struct node" already defined) :

n = malloc(sizeof(struct node));
free(n);
Related