In the code below, even after deleting node (20), if I try to print all the nodes by passing the remote node as a head mask, it prints all the nodes together with the remote node, Can someone explain this behavior with the Garbage Collection in Java? How could it iterate through all the nodes, even if the next element does not exist for the remote node (20)?
Node:
class Node{
int nodeint;
Node next;
public Node(int nodeint){
this.nodeint = nodeint;
}
}
LinkedList
public class linkedlist{
Node head;
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);
newobj.printAllNodes(obj);
obj = newobj.remove();
System.out.println("A node is deleted");
newobj.printAllNodes(obj);
newobj.printHead();
}
}
The output of this code is:
20
5
2
3
4
A node is removed
20
5
2
3
4
This is the true chapter of node: 5
source
share