当前位置:网站首页>[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;
}
边栏推荐
猜你喜欢

PCIE知识点-008:PCIE switch的结构

快递e栈——数组篇小型项目

Go from introduction to practice -- coordination mechanism (note)

今晚战码先锋润和赛道第2期直播丨如何参与OpenHarmony代码贡献

本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献

Tiktok's interest in e-commerce has hit the traffic ceiling?

MYSQL和MongoDB的分析

.NET学习笔记(五)----Lambda、Linq、匿名类(var)、扩展方法

At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions

Go从入门到实战——channel的关闭和广播(笔记)
随机推荐
Codeforces Round #716 (Div. 2)
数组作业题
SQL必需掌握的100个重要知识点:IN 操作符
Yu Wenwen, Hu Xia and other stars take you to play with the party. Pipi app ignites your summer
Go从入门到实战——Context与任务取消(笔记)
Go从入门到实战——接口(笔记)
STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP
Flask----应用案例
Go从入门到实战——CSP并发机制(笔记)
GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法
[LeetCode]161. 相隔为 1 的编辑距离
VMware vSphere esxi 7.0 installation tutorial
Go from entry to practice - dependency management (notes)
Process control task
GBase 8a OLAP分析函数 cume_dist的使用样例
Use the storcli tool to configure raid. Just collect this article
Common methods of string class
01-Golang-环境搭建
White whoring red team goby & POC, how do you call white whoring?
图解基于AQS队列实现的CountDownLatch和CyclicBarrier