当前位置: 首页 > news >正文

148.排序链表

给你链表的头结点head,请将其按升序排列并返回排序后的链表

class Solution { public ListNode sortList(ListNode head) { if (head == null) { return head; } // 计算链表长度 int length = 0; ListNode node = head; // 用临时指针遍历,不改变原头指针 while (node != null) { length++; node = node.next; } ListNode dummyHead = new ListNode(0, head); // 创建哑节点,指向原链表头 // 自底向上归并排序 // subLength表示当前要合并的子链表长度 for (int subLength = 1; subLength < length; subLength <<= 1) { // 每次从头开始处理整个链表 ListNode prev = dummyHead; // prev指向已排序部分的末尾 ListNode curr = dummyHead.next; // curr指向待处理部分的头部 // 遍历整个链表,每次处理两个子链表 while (curr != null) { ListNode head1 = curr; // 第一个子链表的头 // 将curr移动到第一个子链表的末尾 for (int i = 1; i < subLength && curr.next != null; i++) { curr = curr.next; } ListNode head2 = curr.next; // 第二个子链表的头 curr.next = null; // 断开第一个子链表 curr = head2; // curr指向第二个子链表的头部 // 将curr移动到第二个子链表的末尾 for (int i = 1; i < subLength && curr != null && curr.next != null; i++) { curr = curr.next; } ListNode next = null; // 用于保存剩余未处理的链表头部 if (curr != null) { // 如果第二个子链表存在 next = curr.next; // 保存剩余部分 curr.next = null; // 断开第二个子链表 } // 合并两个有序子链表 ListNode merged = merge(head1, head2); // 将合并后的链表连接到已排序部分 prev.next = merged; // 将prev移动到合并后链表的末尾 while (prev.next != null) { prev = prev.next; } curr = next; // curr指向剩余未处理的部分 } } return dummyHead.next; } // 合并两个有序链表 public ListNode merge(ListNode head1, ListNode head2) { ListNode dummyHead = new ListNode(0); // 创建哑节点作为合并后链表的头 ListNode temp = dummyHead; // 用于构建新链表的指针 ListNode temp1 = head1; // 遍历第一个链表的指针 ListNode temp2 = head2; // 遍历第二个链表的指针 // 比较两个链表当前节点的值 while (temp1 != null && temp2 != null) { if (temp1.val <= temp2.val) { temp.next = temp1; temp1 = temp1.next; } else { temp.next = temp2; temp2 = temp2.next; } temp = temp.next; } // 处理空节点 if (temp1 != null) { temp.next = temp1; } else if (temp2 != null) { temp.next = temp2; } return dummyHead.next; } }
http://www.jsqmd.com/news/467460/

相关文章:

  • OpenClaw 小龙虾养成记:手把手教你上线第一只 AI 助手!
  • 如何回收永辉超市购物卡? - 团团收购物卡回收
  • 一图区分MCP,Plugin,Tools,Skills,Hooks/Subagents概念
  • 出海营销大变局:超三成流量向AI迁移,企业如何打破“AI搜索隐形”困局? - 资讯焦点
  • CAN通信栈实战详解(Can通讯原理+配置+实战项目需求)
  • SQLerror注入boolean注入其他注入
  • 高柔性扁平电缆在半导体光刻机与气浮运动平台中的应用与品牌推荐 - 资讯焦点
  • ESP32学习笔记(十)——I2C通信
  • 揭秘AI论文工具隐藏玩法:8款免费神器1小时出10万言,无虚假引用 - 麟书学长
  • 在R语言中,基本的算术运算是数据分析和计算的基础
  • ssm+java2026年毕设社区二手交易平台【源码+论文】
  • 渐变文字的小技巧
  • 装修季必看!迷你考拉自助仓库解决搬家装修物品寄存的仓储难题 - 资讯焦点
  • 深度学习第五节课之半监督食物分类系统下
  • 面向AI全栈工作流的个人工作站构建指南:从硬件选型到系统抉择
  • 量子纠缠就是递归元——朱梁渡劫递归元范式下的量子力学阐释
  • 2026-3-9 数据库
  • 狂神说JAVA面向对象
  • 2026-03-12 GitHub 热点项目精选
  • OpenClaw 凭什么引爆全网?从生活管家到企业大脑,普通人和专业人士的全能手册!
  • 2026 年北京名酒回收推荐榜单:北京振伟老酒回收行 行业标杆 - 资讯焦点
  • GPT-5.4原生计算机操作能力深度解析与智能体开发实战
  • AE插件AI人工智能自动生成音乐音效无需联网 Sound Prompter v1.1.46 Win
  • 前端面试题口语化
  • 【Python】集合
  • 第七章:PX4 的“神经系统”——uORB
  • 男性保健品该怎么选?别被营销迷眼,2026年医生视角权威排行教你判断谁值得信 - 资讯焦点
  • 2026工业烧嘴厂家推荐 适配多行业低氮节能需求 - 资讯焦点
  • 野火STM32_HAL库版课程笔记-串口发送之阻塞接收定长数据
  • 2026年贵州不锈钢管厂家哪家靠谱?品类齐全 质量高适配各类使用场景 - 深度智识库