-2
public void insertion(int data)
    {
        Node new_node = new Node(data);
        if(head==null)
        {
            head=new_node;
        }
        new_node.next=head;
        head=new_node;
    }

I want to insert the new_node when head is null.

I am getting infinite loop of first value which i want to insert in the node

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117

1 Answers1

0

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'snextwhenhead*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;
    }

}
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117