When head == null
is true, you essentially do:
head = new_node;
new_node.next = head;
Think about those lines carefully. After the first line runs, head
is new_node
. With that in mind, the second line is essentially equivalent to
new_node.next = new_node;
Which should highlight the problem. You're setting the new node's tail to itself! That will lead to a cyclic list that will continue infinitely when iterated.
You only want to set head's
nextwhen
head*wasn't*
null` initially:
public void insertion(int data)
{
Node new_node = new Node(data);
if(head==null)
{
head=new_node;
} else {
new_node.next=head; // Only execute these lines if head already existed
head=new_node;
}
}