How to insert a node in the end of the linked list in java

0

 



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



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

public class InsertEnd {

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

public static NodeB insertEnding(NodeB head,int data)
{
NodeB temp=new NodeB(data);
if(head==null)
return temp;
NodeB curr=head;
while(curr.next !=null)
{
curr=curr.next;
}
curr.next=temp;
return head;
}
public static void main(String args[])
{
NodeB head1=new NodeB(10);
NodeB head2=new NodeB(20);
NodeB head3=new NodeB(30);
head1.next=head2;
head2.next=head3;
System.out.println("Items in the list are :- ");
print(head1);
NodeB temp=insertEnding(head1,40);
System.out.println("\nItems in the list after insertion at the beginning are :- ");
print(temp);

}
}

Post a Comment

0Comments
Post a Comment (0)

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

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