# 708     Insert into a Cyclic Sorted List

## 708. [Insert into a Cyclic Sorted List](https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/description/)

## 1. Question

Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to\_any\_single node in the list, and may not be necessarily the smallest value in the cyclic list.

If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the cyclic list should remain sorted.

If the list is empty (i.e., given node is`null`), you should create a new single cyclic list and return the reference to that single node. Otherwise, you should return the original given node.

## 2. Implementation

```java
/*
// Definition for a Node.
class Node {
    public int val;
    public Node next;

    public Node() {}

    public Node(int _val,Node _next) {
        val = _val;
        next = _next;
    }
};
*/
class Solution {
    public Node insert(Node head, int insertVal) {
        if (head == null) {
            Node node = new Node(insertVal);
            node.next = node;
            return node;
        }

        Node curNode = head;

        while (curNode != null && curNode.next != null) {
            if (curNode.val < curNode.next.val) {
                if (curNode.val <= insertVal && insertVal <= curNode.next.val) {
                    break;
                }
            }
             else if (curNode.val > curNode.next.val) {
                if (insertVal > curNode.val || insertVal < curNode.next.val) {
                    break;
                }
            }
            else {
                if (curNode.next == head) {
                    break;
                }
            }
            curNode = curNode.next;
        }

        insertNode(curNode, insertVal);
        return head;
    }

    public void insertNode(Node curNode, int val) {
        if (curNode == null) return;

        Node node = new Node(val);
        node.next = curNode.next;
        curNode.next = node;
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n)，空间复杂度O(1)
