每日一题:循环有序链表的插入
https://leetcode.cn/problems/4ueAj6/
import Entity.*;
public class Solution {
/*
* 头结点只是一个普通结点,并不是有序链表的头部。
* 1. 若链表为空,则直接插入,否则:
* 2. 需要在循环中查找插入位置:
* 2.1. 若插入值为最值,则需要插入到有序链表的头尾;
* 2.2. 否则,需要在链表中查找插入位置,并插入。
* 2.3. 还需要考虑当前链表所有值是否单一,单一的情况下可以插入任意位置。
*/
public Node insert(Node head, int insertVal) {
Node cur=head;
//若链表为空,则直接插入
if(cur==null){
head=new Node(insertVal);
head.next=head;
return head;
}
Node next=head.next;
while(true){
if(isRightPlace(cur.val, next.val, insertVal)){
cur.next = new Node(insertVal, next);
return head;
}
cur=next;
next=next.next;
//在遍历一遍链表后跳出循环
if(cur==head){
break;
}
}
//在遍历一次结束后,节点仍然未被插入,那么说明链表值是单一的,可以插入任意位置
cur.next = new Node(insertVal, next);
return head;
}
private boolean isRightPlace(int curVal, int nextVal, int insertVal){
//若当前值小于等于插入值,且下一值大于等于插入值,则插入值在当前值和下一值之间
if(curVal<=insertVal && nextVal>=insertVal) return true;
//若当前值大于下一值(即当前值为最大值、下一值为最小值)
//遍历到这一步循环还没有return,需要判断插入值是否为最值,若是最值,则插入当前位置。
if(curVal>nextVal && (insertVal>=curVal || insertVal<=nextVal)) return true;
return false;
}
}

浙公网安备 33010602011771号