Delete Nth Node from Circular LinkedList

Delete Nth Node from Circular Linked List

 
To delete the Nth Node from circular Linked List
 

  • Iterate the list till N-1th Node
  • set the N-1 next reference to the next of next N-1th node.

 
Here is the code
 



package com.diaryreaders.datastructures.linkedlist;
public class DeleteNthNodeCircularLinkedList {
public static void main(String[] args) {
CircularLinkedList cll1 = new CircularLinkedList();
CircularLinkedList cll2 = new CircularLinkedList();
CircularLinkedList cll3 = new CircularLinkedList();
CircularLinkedList cll4 = new CircularLinkedList();
CircularLinkedList cll5 = new CircularLinkedList();
cll1.setData(1);
cll2.setData(2);
cll3.setData(3);
cll4.setData(4);
cll5.setData(5);
cll1.setNext(cll2);
cll2.setNext(cll3);
cll3.setNext(cll4);
cll4.setNext(cll5);
cll5.setNext(cll1);
iterate(delete(cll1, 3));
}
private static CircularLinkedList delete(CircularLinkedList head, int n) {
CircularLinkedList currentNode = head;
if (n == 0) {
while (currentNode != null && currentNode.getNext() != head) {
currentNode = currentNode.getNext();
}
head = head.getNext();
currentNode.setNext(head);
return head;
}
int i = 0;
while (currentNode != null && i != n - 1) {
i++;
currentNode = currentNode.getNext();
if (currentNode == head) {
break;
}
}
if (i == n - 1 && currentNode.getNext() != head) {
currentNode.setNext(currentNode.getNext().getNext());
}
return head;
}
private static void iterate(CircularLinkedList head) {
CircularLinkedList cll = head;
while (cll != null) {
System.out.println(cll.getData());
cll = cll.getNext();
if (head == cll) {
break;
}
}
}
}


 
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