当前位置:网站首页>力扣每日一题(链表模拟)
力扣每日一题(链表模拟)
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;
}
}边栏推荐
- C language - linear sequence table
- 剪枝-量化-转onnx中文系列教程
- 能替代ps的修图软件?
- [song] rebirth of me in py introductory training (12): Matplotlib interface and common graphics
- 小技巧-彻底删除U盘中的文件
- Super remote connection management tool: Royal TSX
- Day 3. Suicidal ideation and behavior in institutions of higher learning: A latent class analysis
- C语言-动态内存管理
- 【头歌】重生之我在py入门实训中(9):异常处理
- 【Arduino】重生之Arduino 学僧(1)
猜你喜欢

2022.6.10 STM32MP157串口时钟的学习

制作视频特效必备工具:NUKE 13

Super remote connection management tool: Royal TSX

面试常问Future、FutureTask和CompletableFuture

Live Home 3D Pro interior home design tool

Unity Shader 概述

剪枝-量化-转onnx中文系列教程

AE 3D particle system plug-in: Trapcode particle

geonode geoserver win10 安装教程(亲测)

STM32-FSMC外扩内存SRAM
随机推荐
std::bind与std::function的一些应用
【头歌】重生之我在py入门实训中(7): 函数调用
面试常问Future、FutureTask和CompletableFuture
A photo breaks through the face recognition system: you can nod your head and open your mouth, netizens
Lightroom Classic 2022 v11.4中文版「最新资源」
力扣第一周错题集
Weidongshan digital photo frame project learning (II) displaying Chinese characters on LCD
力扣题解 二叉树(6)
2022.6.10 STM32MP157串口时钟的学习
编程学习记录--第2课【初识C语言】
安全帽反光衣检测识别数据集和yolov5模型
安装windows下的redis
李宏毅 2020 深度学习与人类语言处理 DLHLP-Conditional Generation by RNN and Attention-p22
What has been updated in the Chinese version of XMIND mind map 2022 v12.0.3?
【动态规划----钢条切割问题】
力扣题解 动态规划(4)
Super remote connection management tool: Royal TSX
使用-Wall清除代码隐患
pycharm安装及导入项目注意事项
Day 3. Suicidal ideation and behavior in institutions of higher learning: A latent class analysis