Insert Node at Nth position in Circular LinkedList

Insert Node at Nth position in Circular LinkedList

 
To insert the Node at the nth position in the circular linked list
 

  • Iterate the list till n-1th node.
  • set the next of new node to the next of n-1th node
  • set the next of n-1th node to the new node.

 
Here is the code
 



package com.diaryreaders.datastructures.linkedlist;
public class InsertNthNodeCircularLinkedList {
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(cll1);
iterate(insert(cll1, cll5, 2));
}
private static void iterate(CircularLinkedList head) {
CircularLinkedList cll = head;
while (cll != null) {
System.out.println(cll.getData());
cll = cll.getNext();
if (head == cll) {
break;
}
}
}
private static CircularLinkedList insert(CircularLinkedList head, CircularLinkedList node, int n) {
CircularLinkedList currentNode = head;
// Adding a node at the front of the Circular LinkedList
if (n == 0) {
node.setNext(head);
while (currentNode.getNext() != head) {
currentNode = currentNode.getNext();
}
currentNode.setNext(node);
return node;
}
// Adding node at Nth position
int i = 0;
while (currentNode != null && i != n - 1) {
i++;
currentNode = currentNode.getNext();
if (currentNode == head) {
break;
}
}
if (i == n - 1 && currentNode != head) {
node.setNext(currentNode.getNext());
currentNode.setNext(node);
}
return head;
}
}


 
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