class Solution {
    public Node insert(Node he, int x) {
        Node t=new Node(x);
        t.next=t; // 这一步不要忘记,是个循环链表
        Node ans=he;
        if(he==null) return t;
        // 遍历,得到max和min
        int max=he.val;
        int min=he.val;
        while(he.next!=ans){
            max=Math.max(he.val,max);
            min=Math.min(he.val,min);
            he=he.next;
        }
        // 如果max==min  直接把t挂he后面
        if(max==min){
            t.next=he.next;
            he.next=t;
        }else{
            // 如果max!=min 
            // he遍历到最大值和最小值中间
            // 如果 !(x>=max || x<=min) && !(he.val<x<he.next.val) 就继续遍历
            // 把t插入到当前he
            while(!(he.val==max && he.next.val==min)) he=he.next;
            while(!(x>=max || x<=min) && !(he.val<=x && x<=he.next.val)) he=he.next;
            t.next=he.next;
            he.next=t;
        }
        return ans;
    }
}