当前位置:网站首页>排序的循环链表
排序的循环链表
2022-06-11 18:01:00 【AlbertOS】
引入
给定循环单调非递减列表中的一个点,写一个函数向这个列表中插入一个新元素 insertVal ,使这个列表仍然是循环升序的。
给定的可以是这个列表中任意一个顶点的指针,并不一定是这个列表中最小元素的指针。
如果有多个满足条件的插入位置,可以选择任意一个位置插入新的值,插入后整个列表仍然保持有序。
如果列表为空(给定的节点是 null),需要创建一个循环有序列表并返回这个节点。否则。请返回原先给定的节点。
示例

输入:head = [3,4,1], insertVal = 2
输出:[3,4,1,2]
解释:在上图中,有一个包含三个元素的循环有序列表,你获得值为 3 的节点的指针,我们需要向表中插入元素 2 。新插入的节点应该在 1 和 3 之间,插入之后,整个列表如上图所示,最后返回节点 3 。
解法(C++)
这题是一个任意一个顶点的指针,所以第一个思路就是往下遍历,如果找到一个节点cur满足cur->val <= insertVal <= cur->next->val ,就可以直接插入了;
如果找不到,就说明所有值都比它小或大,所以这个都会插入到边界位置上。
满足insertVal <= cur->next->val <=cur->val(插入值比最小的小)
或者insertVal >= cur->val >= cur->next->val(插入值比最大的大)
/* // Definition for a Node. class Node { public: int val; Node* next; Node() {} Node(int _val) { val = _val; next = NULL; } Node(int _val, Node* _next) { val = _val; next = _next; } }; */
class Solution {
public:
Node* insert(Node* head, int insertVal) {
//判空
if(head == nullptr){
head = new Node(insertVal);
head->next = head ;
return head ;
}
auto cur = head;
while(cur->next !=head){
//如果下一个节点小于当前节点,证明达到了边界位置(末边界就是最大值)
if(cur->next->val < cur->val){
//如果下一个节点大于插入值,证明插入值比最小的小
if(cur->next->val >= insertVal) break;
// 如果当前节点小于插入值,证明插入值比最大值的大
else if(cur->val <= insertVal) break;
}
//如果当前节点小于插入值且下一节点大于插入值,则插入到这个位置
if(cur->val <= insertVal && cur->next->val >= insertVal)
break;
//不满足三个条件则找下一个
cur = cur->next;
}
cur->next = new Node(insertVal,cur->next);
return head;
}
};
边栏推荐
猜你喜欢

網絡安全威脅情報體系

【先收藏,早晚用得到】49个Flink高频面试题系列(一)

NR LDPC 打孔-punctured

Online excel file parsing and conversion to JSON format

SISO decoder for a general (n, n-1) SPC code (supplementary Chapter 3)

【无标题】

async导致函数结果出乎意料,改变原来代码的意图;await is only valid in async functions and the top level bodies of modules

Three steps of ffmpeg CBR precise bitstream control

Upload labs failed to pass the customs halfway and the middle road collapsed
![Spring 2021 daily question [end of week4]](/img/b3/2f5a66b0d4374db3d4db0b71d72f7e.jpg)
Spring 2021 daily question [end of week4]
随机推荐
Reading summary of nacos2.x source code
Why is the UDP stream set to 1316 bytes
SQL statement when the query condition is blank, all data will be queried by default. If it is not blank, the query will be performed according to the condition
Upload labs failed to pass the customs halfway and the middle road collapsed
ACL 2022:评估单词多义性不再困扰?一种新的基准“DIBIMT”
Tle6288r is a 6-channel (150 MOhm) intelligent multi-channel switch using intelligent power technology - keshijin mall
密码学概述
【C】 ATOI function implementation +offsetof implementation + exchange binary odd and even digits
【实用脚本】获取某个文件的行号,然后删除文件内容。
Introduction to social engineering practice
Ctfhub SQL Boolean blind annotation
[C语言]用结构体把最高分的学生输出,可有多个最高分
Is it good or not to open a stock account on the flush? Is it safe?
夜神安装apk,以及bp代理
网络安全威胁情报体系
Using packstack to quickly install openstack
TestPattern error
Simple understanding of events
File class learning
Sa-Token 单点登录 SSO模式二 URL重定向传播会话示例
