一、思路
目标明确:先找到最小节点,再寻找应当插入的位置,特别地要注意当插入值是比 最大值还大的值 或者 是比最小值还小的值 的处理,注意避免进入死循环!!,代码中已经给出详细注释~
二、代码实现
class Solution {
public Node insert(Node head, int insertVal) {
if(head == null) {
Node node = new Node(insertVal);
node.next = node;
return node;
}
Node cur = head;
while (true){ // 寻找最小节点
int preNum = cur.val;
cur = cur.next;
if (cur.val < preNum //由于链表为非递减链表,故当节点值小于其父节点值时即此节点为最小节点
|| cur == head // 特殊情况,若循环一一圈都没找到,说明此时head就指向最小节点
){
break;
}
}
// 开始插入节点
Node begin = cur; // 记录最小节点
while (true){
if (insertVal == cur.val // 当插入值与当前节点值相等时
|| (insertVal > cur.val && insertVal < cur.next.val // // 此插入值应当插入在两个节点之间
|| cur.next == begin // 此时说明插入值是比最大值还大的值或者是比最小值还小的值,应当插入在最小节点的与最大节点之间
)){
Node node = new Node(insertVal);
node.next = cur.next;
cur.next = node;
break;
}
cur = cur.next;
}
return head;
}
}
运行结果: