I'm going through linked list interview questions on Geeks4Geeks, and there is a question about deleting a node in a singly linked list. It should not modify the head node, and it should not return pointer to the head node.
I understand that since the head node can not be modified, if delete the head node, essentially we need to copy everything from the second node to the head node and free the memory address of the second node. In C implementation it's an explicit call to free(). But in Java, does system.gc() necessary in the code, or it's just an implication that garbage collector should run?
Here is the code snippet (first argument is the head node, second is the node to be deleted):
void deleteNode(Node node, Node n) {
// When node to be deleted is head node
if (node == n) {
if (node.next == null) {
System.out.println("There is only one node. The list "
+ "can't be made empty ");
return;
}
/* Copy the data of next node to head */
node.data = node.next.data;
// store address of next node
n = node.next;
// Remove the link of next node
node.next = node.next.next;
// free memory
System.gc();
return;
}
// When not first node, follow the normal deletion process
// find the previous node
Node prev = node;
while (prev.next != null && prev.next != n) {
prev = prev.next;
}
// Check if node really exists in Linked List
if (prev.next == null) {
System.out.println("Given node is not present in Linked List");
return;
}
// Remove node from Linked List
prev.next = prev.next.next;
// Free memory
System.gc();
return;
}
I just can't see the point of explicitly calling System.gc() here if garbage collection in Java is automatic. From my understanding, a call to System.gc() does not guarantee that the garbage collector would run (is that the case?). So is it just a conceptual implication?
Thanks!