当前位置:网站首页>力扣每日一题(链表模拟)
力扣每日一题(链表模拟)
2022-07-27 05:21:00 【最后一只三脚兽】
剑指 Offer II 029. 排序的循环链表 - 力扣(LeetCode)

看了一些题解,感觉他们分类有点太细了,导致代码很多,其实就是三种情况
- head为null时,直接把head值改为需求值再让next指向自己即可
- 也是最一般情况,插入节点在一小一大两节点中间,只要找到一个节点val小于等于所插节点且该节点的next的val大于等于所插节点即可
- 极端情况,也就是所插节点恰好是最大值或是最小值,我们只要找到最大节点然后把插入的节点放最大节点后面即可(例如1,2,3,4 如果插入的是5就放4后,如果插入的是0也是放4后)。极端情况就是循环了一遍没找到第二种情况,此时就是极端情况
class Solution {
public Node insert(Node head, int insertVal) {
//节点为空
if(head == null){
head = new Node(insertVal);
head.next = head;
return head;
}
Node tmp = head;
Node max = head;
while(true){
//保留最大节点,避免二次遍历
max = tmp.val >= max.val?tmp:max;
//判断是否是一般情况
if(tmp.val<=insertVal && tmp.next.val>=insertVal){
Node node = new Node(insertVal,tmp.next);
tmp.next = node;
return head;
}
tmp = tmp.next;
//回到头节点,遍历结束
if(tmp==head){
break;
}
}
//极端情况
Node node = new Node(insertVal,max.next);
max.next = node;
return head;
}
}边栏推荐
猜你喜欢

李宏毅 2020 深度学习与人类语言处理 DLHLP-Conditional Generation by RNN and Attention-p22

C# Json编码在TCP通讯中的一些使用总结

安全帽反光衣检测识别数据集和yolov5模型

ps 2022 六月更新,都新增了哪些功能

When multiple formulas in latex share a sequence number

LaTeX中多个公式公用一个序号时

STM32-FSMC外扩内存SRAM

Super remote connection management tool: Royal TSX

QGIS系列(1)-QGIS(server-apache) win10安装

Kaggle调用自定义模块方法
随机推荐
【头歌】重生之我在py入门实训中(1)
AE 3D particle system plug-in: Trapcode particle
[first song] rebirth of me in py introductory training (4): Circular program
人月神话阅读笔记
A photo breaks through the face recognition system: you can nod your head and open your mouth, netizens
C语言-文件操作
韦东山 数码相框 项目学习(三)freetype的移植
【头歌】重生之CNN图片分类基础
Lightroom classic 2022 v11.4 Chinese version "latest resources"
基于C#的Winform对Access数据库进行操作(mdb结尾)
【头歌】重生之我在py入门实训中(5):列表
常见的SQL优化方法
[first song] rebirth of me in py introductory training (3): if conditional sentence
1 semi automatic crawler
数据库索引的一些说明以及使用
Day 2. Depressive symptoms, post-traumatic stress symptoms and suicide risk among graduate students
使用Markdowm
Li Kou daily question sword finger offer II 091. paint the house
力扣题解 单调栈
C语言扫雷最新 递归展开 超详解(附源码)