给定循环单调非递减列表中的一个点,写一个函数向这个列表中插入一个新元素 insertVal ,使这个列表仍然是循环升序的。
给定的可以是这个列表中任意一个顶点的指针,并不一定是这个列表中最小元素的指针。
如果有多个满足条件的插入位置,可以选择任意一个位置插入新的值,插入后整个列表仍然保持有序。
如果列表为空(给定的节点是 null),需要创建一个循环有序列表并返回这个节点。否则。请返回原先给定的节点。
public Node insert(Node head, int insertVal) {
if (head==null){
Node node = new Node(insertVal);
node.next=node;
return node;
}
Node cur = head;
while(cur.next!=head){
if (cur.next.val<cur.val){
if (cur.next.val>=insertVal){
//最小值
//[3,5,1] 0 ==> [3,5,0,1]
break;
}else if (cur.val<=insertVal){
//最大值
//[3,5,1] 6 ==>[3,5,6,1]
break;
}
}
//中间顺序插入
//[1,3,5] 2 ==> [1,2,3,5]
if (cur.val<=insertVal&&cur.next.val>=insertVal){
break;
}
//移动指针
cur=cur.next;
}
//插入新节点
cur.next=new Node(insertVal,cur.next);
return head;
}