当前位置:网站首页>【链表】148. 排序链表
【链表】148. 排序链表
2022-04-21 11:32:00 【不爱研究的研究僧】
题目:
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

题解:
时间复杂度是O(nlogn) 的排序算法包括归并排序、堆排序和快速排序(快速排序的最差时间复杂度是 O(n^2),其中最适合链表的排序算法是归并排序。
这里用递归的方式进行归并排序。
步骤:
1.找到链表的中点,以中点为分界,将链表拆分成两个子链表。寻找链表的中点可以使用快慢指针的做法,快指针每次移动 2 步,慢指针每次移动 1 步,当快指针到达链表末尾时,慢指针指向的链表节点即为链表的中点。
2.对两个子链表分别排序。
3.将两个排序后的子链表合并,得到完整的排序后的链表。可以使用「21. 合并两个有序链表」的做法,将两个有序的子链表进行合并。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null; //切开成两个链表,前一个链表要和后一个链表断关系
ListNode h = new ListNode(0);
ListNode res = h; //最后的结果放虚节点后面
ListNode left = sortList(head); //head是前一个链表的起点,left为排序完的起点
ListNode right = sortList(tmp); //tmp是后一个链表的起点,right为排序完的起点
while (left != null && right != null) { //和21.合并两个有序链表的步骤一样
if (left.val < right.val) {
h.next = left;
left = left.next;
} else {
h.next = right;
right = right.next;
}
h = h.next; //结果也要后移一位
}
h.next = left == null ? right : left;
return res.next;
}
}
参考:力扣
版权声明
本文为[不爱研究的研究僧]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43955488/article/details/124317223
边栏推荐
- L3-028 Sensen tourism (30 points) (Dijkstra + reverse drawing + details)
- Intelligent party building platform system development, and promote the construction of "Internet plus party building"
- 阅读材料:信息技术年谱
- Xinghan future cloud native basic governance platform schedulx v1 1.0 heavy release to help enterprises reduce costs and increase efficiency
- Unix哲学与高并发
- Spark快速入门系列(5) | Spark环境搭建—standalone(2) 配置历史日志服务器
- 关于Winxp U盘无法复制磁盘写保护解决办法
- Redis interview questions
- JSTL -- JSP standard tag library
- 开源文化依旧熠熠生辉 —— 在openEuler社区,有技术、有idea,你就是主角
猜你喜欢
随机推荐
分享:Web 网页设计规范
连接服务器报错No supported authentication methods available
Redis cluster mode
Decorator modifier / binary array of ES6 new feature (8)
AES encryption and decryption with cryptojs
(coordinate dynamic programming) lintcode medium 248 · count the number of numbers smaller than a given integer
华为云MySQL云数据库,轻松助力数据上云
LC刷题第四天
互联网快讯:拓荆科技成功登陆科创板;极米H3S、极米Z6X Pro持续热销;盒马在上海启动“流动超市”
ES6新特性(8)之Decorator修饰器/二进制数组
Redis interview questions
Écrire un dictionnaire de tableaux au format CSV
循环队列的长度「In DataStructure」
美国加息人民币贬值,这类产品却迎来蜜月期
I18N 国际化
分享 Map 对象和普通对象的 7 个区别
MQ processus et contenu pertinents
塔米狗项目解读|海南奥特莱斯旅业开发有限公司100%股权转让
Brutally crack the latest JVM interview questions of meituan
leaflet军事标绘-突击方向修改(leaflet篇.90)


![[binary number] symmetric binary tree](/img/15/a1285ae7f31dd2e9f7b00350b1fdc6.png)





