In the code below, even after deleting a node (20) if I try to print all the nodes by passing deleted node as head in disguise, it is printing all the nodes along with the deleted node. Can someone please explain this behavior along with Garbage Collection in Java? How was it able to iterate all the nodes even though there is no next element for the deleted node (20)?
Node:
class Node{
int nodeint;
Node next;
public Node(int nodeint){
this.nodeint = nodeint;
}
}
LinkedList:
public class linkedlist{
Node head;
//Node next;
public linkedlist(Node obj){
this.head = obj;
}
public Node addnodes(int news){
Node newlink = new Node(news);
newlink.next = head;
head = newlink;
return head;
}
public void printAllNodes(Node obj){
Node current = obj;
while(current!=null){
System.out.println(current.nodeint);
current = current.next;
}
}
public Node remove(){
Node temp = head;
head = head.next;
return temp;
}
public void printHead(){
System.out.println("This is the present head node"+head.nodeint);
}
public static void main(String [] args){
Node obj1 = new Node(2);
Node obj2 = new Node(3);
Node obj3 = new Node(4);
obj1.next = obj2;
obj2.next = obj3;
obj3.next = null;
linkedlist newobj = new linkedlist(obj1);
Node obj = null;
obj = newobj.addnodes(5);
obj =newobj.addnodes(20);
//System.out.println(obj.nodeint);
newobj.printAllNodes(obj);
obj = newobj.remove();
System.out.println("A node is deleted");
newobj.printAllNodes(obj);
newobj.printHead();
}
}
Output of this code:
20
5
2
3
4
A node is deleted
20
5
2
3
4
This is the present head node: 5
To delete a node from linked list, we need to do following steps. 1) Find previous node of the node to be deleted. 2) Change the next of previous node. 3) Free memory for the node to be deleted. In this instance we remove the node where C is the Data.
next pointer of the last node is NULL, so if the next current node is NULL, we have reached the end of the linked list. In all of the examples, we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below:
In order to delete the node, which is present after the specified node, we need to skip the desired number of nodes to reach the node after which the node will be deleted. We need to keep track of the two nodes.
The task is to print the elements of the second linked list according to the position pointed out by the data in the nodes of the first linked list. For example, if the first linked list is 1->2->5 then you have to print the 1 st, 2 nd and 5 th elements of the second linked list. Attention reader! Don’t stop learning now.
The node 20 has still reference to the next node i.e node 5 in this case. It is not related to garbage collection. If you want that behavior set temp.next == null in your remove method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With