Insert At Beginning of DoublyLinkedList

Insert At the Beginning of DoublyLinkedList

 
Insert a node at the beginning of the DoublyLinkedList can be done in two steps:
 

  • Update the next pointer of new Node to the current head Node and previous reference of new node to NULL.

 



 

  • Update the previous reference of head Node to the new Node and make new Node as head.

 



 
Here is the code:
 



package com.diaryreaders.datastructures.LinkedList;
public class DoublyLinkedListInsertAtBeginning {
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 = insertAtBeginning(dll1, dll5);
print(dll6);
}
private static void print(DoublyLinkedList dll6) {
while (null != dll6) {
System.out.println(dll6.getData());
dll6 = dll6.getNext();
}
} 
private static DoublyLinkedList insertAtBeginning(DoublyLinkedList dll1, DoublyLinkedList dll5) {
if (dll1 == null) {
return dll5;
}
dll5.setNext(dll1);
dll1.setPrev(dll5);
return dll5;
}
}


 
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