In this blog we will see how to insert a node after kth position in the doubly linked list.
class Node
{
int data;
Node prev;
Node next;
Node(int data)
{
this.data=data;
this.prev=null;
this.next=null;
}
}
public class InsertAfterKthDLL
{
public static void print(Node head)
{
Node curr=head;
while(curr != null)
{
System.out.print(curr.data+" ");
curr=curr.next;
}
}
public static Node insertAfterK(Node head,int k,int data)
{
Node temp=new Node(data);
Node curr=head;
for(int i=0;i<k;i++)
{
curr=curr.next;
}
temp.next=curr.next.next;
temp.prev=curr;
curr.next=temp;
curr.next.prev=temp;
return head;
}
public static void main(String args[])
{
Node head=new Node(10);
Node temp1=new Node(20);
Node temp2=new Node(30);
head.next=temp1;
temp1.prev=head;
temp1.next=temp2;
temp2.prev=temp1;
print(head);
head=insertAfterK(head, 1, 1);
System.out.println("\n");
print(head);
head=insertAfterK(head, 1, 15);
System.out.println("\n");
print(head);
}
}