Insert Node At N position of DoublyLinkedList

Insert A Node at N position of DoublyLinkedList

 
To insert a Node at n position
 

  • Traverse the list till n-1 position
  • Keep the reference of the LinkedList from nth position to the temp variable.
  •  N-1 Node next reference to the new node
  • New Node next reference to the temp variable and temp variable prev reference to the new node reference.

 
Here is the code.
 



package com.diaryreaders.datastructures.linkedlist;
public class DoublyLinkedListInsertAtMiddle {
public static void main(String[] args) {
DoublyLinkedList dll1 = new DoublyLinkedList();
DoublyLinkedList dll2 = new DoublyLinkedList();
DoublyLinkedList dll3 = new DoublyLinkedList();
DoublyLinkedList dll4 = new DoublyLinkedList();
DoublyLinkedList dll5 = new DoublyLinkedList();
dll5.setData(5);
dll1.setPrev(null);
dll1.setNext(dll2);
dll1.setData(1);
dll2.setPrev(dll1);
dll2.setNext(dll3);
dll2.setData(2);
dll3.setPrev(dll2);
dll3.setNext(dll4);
dll3.setData(3);
dll4.setPrev(dll3);
dll4.setNext(null);
dll4.setData(4);
DoublyLinkedList dll6 = insertMiddle(dll1, dll5, 3);
print(dll6);
}
private static void print(DoublyLinkedList dll6) {
while (dll6 != null) {
System.out.println(dll6.getData());
dll6 = dll6.getNext();
}
}
private static DoublyLinkedList insertMiddle(DoublyLinkedList dll1, DoublyLinkedList dll5, int n) {
int count = 0;
if (n == 0){
dll5.setNext(dll1);
dll1.setPrev(dll5);
return dll5;
}
DoublyLinkedList temp = dll1;
while (temp.getNext() != null && count != n - 1) {
temp = temp.getNext();
count++;
}
if (count == n - 1) {
DoublyLinkedList temp1 = temp.getNext();
temp.setNext(dll5);
dll5.setPrev(temp);
dll5.setNext(temp1);
if (temp1 !=null){
temp1.setPrev(dll5);
}
}
return dll1;
}
}


 
Output:

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON