剑指 Offer II 029. 排序的循环链表 - 力扣(LeetCode)
看了一些题解,感觉他们分类有点太细了,导致代码很多,其实就是三种情况
- head为null时,直接把head值改为需求值再让next指向自己即可
- 也是最一般情况,插入节点在一小一大两节点中间,只要找到一个节点val小于等于所插节点且该节点的next的val大于等于所插节点即可
- 极端情况,也就是所插节点恰好是最大值或是最小值,我们只要找到最大节点然后把插入的节点放最大节点后面即可(例如1,2,3,4 如果插入的是5就放4后,如果插入的是0也是放4后)。极端情况就是循环了一遍没找到第二种情况,此时就是极端情况
class Solution {
public Node insert(Node head, int insertVal) {
//节点为空
if(head == null){
head = new Node(insertVal);
head.next = head;
return head;
}
Node tmp = head;
Node max = head;
while(true){
//保留最大节点,避免二次遍历
max = tmp.val >= max.val?tmp:max;
//判断是否是一般情况
if(tmp.val<=insertVal && tmp.next.val>=insertVal){
Node node = new Node(insertVal,tmp.next);
tmp.next = node;
return head;
}
tmp = tmp.next;
//回到头节点,遍历结束
if(tmp==head){
break;
}
}
//极端情况
Node node = new Node(insertVal,max.next);
max.next = node;
return head;
}
}