How to insert a node in the linked list in java

0

 


In this article we will how to add an element in the linked list.



class NodeC
{
int data;
NodeC next;
NodeC(int data)
{
this.data=data;
this.next=null;
}
}

public class Insertion {

public static void print(NodeC head)
{
NodeC curr=head;
while(curr !=null)
{
System.out.print(curr.data+" ");
curr=curr.next;
}
}

public static NodeC insertBeg(NodeC head,int data)
{
NodeC temp=new NodeC(data);
temp.next=head;
return temp;
}

public static NodeC insertEnd(NodeC head,int data)
{
NodeC temp=new NodeC(data);
if(head.next==null)
return temp;
NodeC curr=head;
while(curr.next !=null)
curr=curr.next;
curr.next=temp;
return head;
}

public static void main(String a[])
{
NodeC head1=new NodeC(1);
NodeC head2=new NodeC(2);
NodeC head3=new NodeC(3);
NodeC head4=new NodeC(4);
head1.next=head2;
head2.next=head3;
head3.next=head4;
System.out.println("List is :- ");
print(head1);
head1=insertBeg(head1,0);
System.out.println("\nList after insertion at beginning is :- ");
print(head1);
head1=insertEnd(head1,5);
System.out.println("\nList after insertion at ending is :- ");
print(head1);
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !