Delete Nth Node from DoublyLinkedList

Delete Nth Node from DoublyLinkedList

 
To delete Nth Node from DoublyLinkedList
 

  • Iterate the list till N-1 position.
  • set the next reference to the  next of next reference of N-1th node.
  • throw exception in case N is out of scope i.e. < 0 or greater than length of List

 

OR

 

  • Iterate the list till Nth position
  • set the next reference of prev reference of Nth node to the next reference of Nth node.
  • throw exception in case N is out of scope i.e. < 0 or greater than length of List

 
Here is the code
 



package com.diaryreaders.datastructures.linkedlist;
public class DeleteNodeLinkedList {
public static void main(String[] args) {
DoublyLinkedList dll1 = new DoublyLinkedList();
DoublyLinkedList dll2 = new DoublyLinkedList();
DoublyLinkedList dll3 = new DoublyLinkedList();
DoublyLinkedList dll4 = new DoublyLinkedList();
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 = deleteNode(dll1, 2, 0);
print(dll6);
}
private static void print(DoublyLinkedList dll6) {
while (dll6 != null) {
System.out.println(dll6.getData());
dll6 = dll6.getNext();
}
}
private static DoublyLinkedList deleteNode(DoublyLinkedList dll1, int n, int i) {
if (n == 0) {
return dll1.getNext();
}
if (dll1 == null || n < 0) {
return dll1; // ideally it should throw an exception
}
if (n == i) {
dll1.getPrev().setNext(dll1.getNext());
return dll1;
}
deleteNode(dll1.getNext(), n, ++i);
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