Search⌘ K
AI Features

Problem: Insert into a Sorted Circular Linked List

Explore how to insert a new node into a sorted circular linked list by traversing nodes and identifying the correct insertion point. Learn to handle cases such as empty lists, all identical values, and the wrap-around from maximum to minimum values. This lesson helps develop efficient linked list manipulation with constant space complexity.

Statement

You are given a node head of a sorted circular linked list, where the values are arranged in non‑descending order. The provided head reference may point to any node in the circular list and does not necessarily correspond to the node with the smallest value.

Write a function to insert a new node with the value insertVal into the list so that the circular list remains sorted in non‑descending order. If multiple valid insertion positions exist, you may choose any one of them.

If the list is empty (i.e., head is null), create a new single‑node circular list containing insertVal and return a reference to that node. Otherwise, return the originally given head node.

Note: The linked list is circular, meaning the last node’s next pointer connects back to the first node.

Constraints:

  • The number of nodes in the list is in the range [0,5×10 ...