当前位置:网站首页>[Sword Offer II]剑指 Offer II 029. 排序的循环链表
[Sword Offer II]剑指 Offer II 029. 排序的循环链表
2022-06-27 19:35:00 【阿飞算法】
题目
剑指 Offer II 029. 排序的循环链表
给定循环单调非递减列表中的一个点,写一个函数向这个列表中插入一个新元素 insertVal ,使这个列表仍然是循环升序的。
给定的可以是这个列表中任意一个顶点的指针,并不一定是这个列表中最小元素的指针。
如果有多个满足条件的插入位置,可以选择任意一个位置插入新的值,插入后整个列表仍然保持有序。
如果列表为空(给定的节点是 null),需要创建一个循环有序列表并返回这个节点。否则。请返回原先给定的节点。
示例 1:
输入:head = [3,4,1], insertVal = 2
输出:[3,4,1,2]
解释:在上图中,有一个包含三个元素的循环有序列表,你获得值为 3 的节点的指针,我们需要向表中插入元素 2 。新插入的节点应该在 1 和 3 之间,插入之后,整个列表如上图所示,最后返回节点 3 。
示例 2:
输入:head = [], insertVal = 1
输出:[1]
解释:列表为空(给定的节点是 null),创建一个循环有序列表并返回这个节点。
示例 3:
输入:head = [1], insertVal = 0
输出:[1,0]
提示:
0 <= Number of Nodes <= 5 * 10^4
-10^6 <= Node.val <= 10^6
-10^6 <= insertVal <= 10^6
方法1:遍历
- 找递增的两个点之间
- 找旋转点
public ListNode insert(ListNode head, int insertVal) {
if (head == null) {
ListNode insertNode = new ListNode(insertVal);
insertNode.next = insertNode;
return insertNode;
}
ListNode cur = head;
while (cur.next != head) {
if (cur.val < cur.next.val) {
if (insertVal >= cur.val && insertVal <= cur.next.val) {
insert(insertVal, cur);
return head;
}
}
if (cur.val > cur.next.val) {
if ((insertVal < cur.val && insertVal < cur.next.val) || insertVal > cur.val) {
insert(insertVal, cur);
return head;
}
}
cur = cur.next;
}
insert(insertVal, cur);
return head;
}
private static void insert(int insertVal, ListNode cur) {
ListNode insertNode = new ListNode(insertVal);
ListNode nxt = cur.next;
cur.next = insertNode;
insertNode.next = nxt;
}
边栏推荐
- JVM memory structure when creating objects
- 微服务之远程调用
- 有时间看看ognl表达式
- Go从入门到实战——所有任务完成(笔记)
- Special tutorial - Captain selection game
- OpenSSL 编程 二:搭建 CA
- 集合代码练习
- 本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
- 互联网 35~40 岁的一线研发人员,对于此岗位的核心竞争力是什么?
- 100 important knowledge points that SQL must master: using functions to process data
猜你喜欢
随机推荐
Go从入门到实战——任务的取消(笔记)
win11桌面出现“了解此图片”如何删除
Use the storcli tool to configure raid. Just collect this article
ABC-Teleporter Setting-(思维+最短路)
matlab查找某一行或者某一列在矩阵中的位置
JVM memory structure when creating objects
Go从入门到实战——协程机制(笔记)
富文本 考试 填空题
Tiktok's interest in e-commerce has hit the traffic ceiling?
MYSQL和MongoDB的分析
石子合并问题分析
[LeetCode]186. 翻转字符串里的单词 II
图解基于AQS队列实现的CountDownLatch和CyclicBarrier
跟我一起AQS SOS AQS
Little known MySQL import data
Process control task
Scrum和看板的区别
本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
IO stream code
SQL必需掌握的100个重要知识点:创建计算字段





![[LeetCode]动态规划解分割数组II[Arctic Fox]](/img/a1/4644206db3e14c81f9f64e4da046bf.png)



