In this article we will how to add an element in the beginning of the linked list.
class NodeA
{
int data;
NodeA next;
NodeA(int data)
{
this.data=data;
this.next=null;
}
}
public class InsertBeg {
public static void print(NodeA head)
{
NodeA curr=head;
while(curr !=null)
{
System.out.print(curr.data+" ");
curr=curr.next;
}
}
public static NodeA insertbegin(NodeA head,int data)
{
NodeA temp=new NodeA(data);
temp.next=head;
return temp;
}
public static void main(String args[])
{
NodeA head1=new NodeA(10);
NodeA head2=new NodeA(20);
NodeA head3=new NodeA(30);
head1.next=head2;
head2.next=head3;
System.out.println("Items in the list are :- ");
print(head1);
NodeA temp=insertbegin(head1,40);
System.out.println("\nItems in the list after insertion at the beginning are :- ");
print(temp);
}
}