888465. Insertion at specific position in circular linked list

Easy

Here is a detailed Markdown blog post for the problem "Insertion at specific position in circular linked list":

Insertion at specific position in circular linked list

Summary

In this problem, we are given a circular linked list and asked to insert a new node at a specific position. The key concept involved is handling the circular nature of the linked list, ensuring that the insertion does not break the circular property.

Detailed Explanation

To solve this problem, we will first need to locate the node at the specified position. Since it's a circular linked list, we can't simply traverse the list from the beginning as we would with a regular linked list. Instead, we'll use a combination of traversing and updating our current node.

Here's a step-by-step breakdown of the solution:

  1. Initialize three pointers: current, new_node, and prev. Set current to the head of the circular linked list, new_node to the new node we want to insert, and prev to null.
  2. Traverse the circular linked list until we reach the node at the specified position. Keep track of the previous node in prev.
  3. Update prev's next pointer to point to new_node, effectively inserting new_node between prev and current.
  4. If the new node is the last one inserted, update its next pointer to the head of the circular linked list (i.e., the current node) to maintain the circular property.

Time complexity: O(n), where n is the number of nodes in the circular linked list. Space complexity: O(1), as we only use a constant amount of space to store our pointers and temporary variables.

Here's an ASCII art diagram to help illustrate the process:

    +--------+
    |  A   |
    +--------+-> B
    |  B   |
    +--------+-> C
    |  C   |
    +--------+-> ...
    |  ...  |
    +--------+-> A (head of circular linked list)

Optimized Solutions

Java

View on GeeksforGeeks
public Node insertAtPosition(Node head, int position) {
    if (position == 0) {
        // handle edge case where new node should be the head
        return new_node;
    }

    Node current = head;
    Node prev = null;

    for (int i = 1; i < position; i++) {
        prev = current;
        current = current.next;
    }

    Node new_node = // create new node

    prev.next = new_node;
    new_node.next = current;

    return head;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.