每日一题:循环有序链表的插入
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;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端