# Insert into a Cyclic Sorted List

## Question ([LI.599](http://www.lintcode.com/en/problem/insert-into-a-cyclic-sorted-list/#))

> Given a random node from a sorted circular linked list, insert a new value into a list and maintain the sorted property. Return the new node.

Node definition?\
Positive values only? No.\
Allow duplicates? Yes.

## Example

```
I: 3->5->1->, 4
O: 3->4->5->1->

I: null, 5
O: 5->

I: 5->, 6
O: 5->6->

I: 5->6->1->, 0
O: 5->6->0->1->
```

## Analysis

Normal case:\
insert when $$val\_{i-1} <= newval <= val\_{i}$$

Corner case:\
insert before start when new\_val is min or max

## Code

```java
public ListNode insert(ListNode node, int value) {
    ListNode newNode = new ListNode(value);
    if (node == null) {
        newNode.next = newNode;
        return newNode;
    }
    ListNode start = findStart(node);
    ListNode prev = start, cur = start.next;
    while (cur != start) {
        if (prev.val <= value && value <= cur.val) {
            break;
        }
        prev = cur;
        cur = cur.next;
    }
    // insert new node
    prev.next = newNode;
    newNode.next = cur;
    return newNode;
}

// find the first smallest node in a CLL
private ListNode findStart(ListNode node) {
    ListNode prev = node, cur = node.next;    
    while (cur != node) {
        if (prev.val > cur.val) {
            break;
        }
        prev = cur; 
        cur = cur.next;
    }
    return cur;
}
```

Note: It is possible to write the solution in one iteration. Then the code has to check for the min/max case explicitly.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zedive.gitbook.io/project-l/part-1/basic_data_structure/linked_list/circular-linked-list/insert-into-a-cyclic-sorted-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
