# 708. Insert into a Cyclic Sorted List

lpy1990
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.

In the figure above, there is a cyclic sorted list of three elements.
You are given a reference to the node with value 3, and we need to
insert 2 into the list.

The new node should insert between node 1 and node 3. After the
insertion, the list should look like this, and we should still return
node 3.

## 思路

case1 node.val < target < node.next.val
case2 node.val <= MinNode.val
case3 node.val >= MaxNode.val

### 代码

``````class Solution {
public Node insert(Node head, int insertVal) {
Node target = new Node(insertVal);
target.next = target;
return target;
}
while (p.val < p.next.val) {
p = p.next;
}
if (p.next.val >= insertVal) { //target比最小的数字还小
insertNode(p, target);
}
p = p.next;
}
while (p.val < insertVal && p.next.val < insertVal && p.next.val > p.val) {
p = p.next;
}
if (p.next.val > p.val && p.next.val < insertVal) { //target在p和p.next之间
insertNode(p.next, target);

} else { //target大于最大值,
insertNode(p, target);
}
}
public void insertNode(Node head, Node target) {
}
}``````

## 代码

``````class Solution {
public Node insert(Node head, int insertVal) {
Node target = new Node(insertVal);
target.next = target;
return target;
}
if (p.val < p.next.val) {
if (p.val <= insertVal && p.next.val >= insertVal) {
insertNode(p, target);
}

} else if (p.val > p.next.val) {
if (insertVal > p.val || insertVal < p.next.val) {
insertNode(p, target);
}
} else {
if (p.val == insertVal) {
insertNode(p, target);
}
}
p = p.next;
}
//跳出, 说明所有的node的值都相同
insertNode(p, target);