Insert the element at given index in Linked list in java.
class Node{
int val;
Node next;
Node(int val){
this.val=val;
}
}
class Sll{
Node head;
Node tail;
int size;
void insertAtIndex(int x,int val){
if(x==0){
Node temp = new Node(val);
head=temp;
size++;
return;
}
if(x<0 || x>size){
System.out.println("invalid index");
return;
}
if(x==size){
Node tail=head;
Node temp=new Node(val);
for(int i=1; i<=x-1; i++){
tail=tail.next;
}
tail.next=temp;
tail=temp;
size++;
return;
}
Node temp =new Node(val);
Node trv= head;
for(int i=1; i<=x-1; i++){
trv=trv.next;
}
temp.next=trv.next;
trv.next=temp;
size++;
}
void display(){
Node temp=head;
while(temp!=null) {
System.out.print(temp.val+" ");
temp=temp.next;
}
System.out.println();
}
void size(){
System.out.println("size is= "+size);
}
}
public class Implement {
public static void main(String[] args) {
Sll list = new Sll();
list.insertAtIndex(0,45);
list.display();
list.size();
list.insertAtIndex(1,55);
list.display();
list.size();
list.insertAtIndex(1,50);
list.display();
list.size();
}
}
output ->
45
size is= 1
45 55
size is= 2
45 50 55
size is= 3
Comments
Post a Comment