Skip to main content
Back to problems
#708
Medium Algorithms

Insert into a sorted circular linked list

Linked List
38.5% acceptance
Mar 31, 2026
1339
801
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list. If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted. If the list is empty (i.e., the given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node.

Solution

C++
Time O(n)
Space O(1)
LeetCode
solution.cpp
/*
// Definition for a Node.
class Node {
public:
  int val;
  Node* next;

  Node() {}

  Node(int _val) {
    val = _val;
    next = NULL;
  }

  Node(int _val, Node* _next) {
    val = _val;
    next = _next;
  }
};
*/

class Solution {
public:
  Node* insert(Node* head, int insertVal) {
    Node* newNode = new Node(insertVal);
    if (!head) {
      newNode->next = newNode;
      return newNode;
    }
    Node* cur = head;
    while (true) {
      if (cur->val <= insertVal && insertVal <= cur->next->val) break;
      if (cur->val > cur->next->val) {
        if (insertVal >= cur->val || insertVal <= cur->next->val) break;
      }
      cur = cur->next;
      if (cur == head) break;
    }
    newNode->next = cur->next;
    cur->next = newNode;
    return head;
  }
};