Insert At End of DoublyLinkedList

Insert At End of LinkedList

 
Inserting the node at the end of the DoublyLinkedList
 

  • Traverse the list till the end of the LinkedList.
  • Update the last node of the LinkedList next reference to the new Node
  • Update the new Node previous reference to the last Node of the LinkedList.

 
Here is the code:
 



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