Write a program to insert a new node at the middle of the circular Linked List in Java

Here's an implementation of inserting a new node in the middle of a circular linked list in Java: 

 

class Node {
    int data;
    Node next;
    
    Node(int data) {
        this.data = data;
    }
}

class CircularLinkedList {
    Node head;
    
    public void insertAtMiddle(int data) {
        Node newNode = new Node(data);
        Node slow = head;
        Node fast = head.next;
        
        while (fast != head && fast.next != head) {
            slow = slow.next;
            fast = fast.next.next;
        }
        
        newNode.next = slow.next;
        slow.next = newNode;
    }
}

In this implementation, we first define a Node class that represents a node in the linked list, with data and a reference to the next node. We then define a CircularLinkedList class that has a head node and a insertAtMiddle method to insert a new node in the middle.

To find the middle node, we use two pointers - a slow pointer and a fast pointer. The slow pointer moves one step at a time while the fast pointer moves two steps at a time. This way, when the fast pointer reaches the end of the list, the slow pointer will be pointing to the middle node.

Finally, we update the links to insert the new node in the middle. The new node's next reference is set to the next node of the slow pointer, and the slow pointer's next reference is set to the new node.

Submit Your Programming Assignment Details