888443. Insertion in an empty circular linked list

Easy

Insertion in an empty circular linked list

Summary

Inserting a new node into an empty circular linked list requires a different approach than inserting nodes into a linearly linked list. The key concept involved is circular linking, where the last node points back to the first node.

Detailed Explanation

To insert a new node into an empty circular linked list, we will create a new node and then link it to the existing nodes in the list. Since there are no existing nodes initially, we can simply point the new node to itself to form a circle.

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

  1. Create a new node with some initial value.
  2. Set the next pointer of the new node to itself (since it's the only node in the list).
  3. Return the new node as the head of the circular linked list.

The time complexity for this operation is O(1) because we're not traversing any nodes, just creating a new one and linking it to itself.

The space complexity is also O(1) because we're using a constant amount of space to store the new node's data.

Optimized Solutions

Java

View on GeeksforGeeks
public Node insert(Node head) {
    if (head == null) {
        return new Node(data);
    }
    // handle non-empty list case here...
}

DevExCode

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

© 2026 DevExCode. All rights reserved.