148. 排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
解题思路
我们可以使用归并排序的思想来对链表进行排序。
具体步骤如下:
1、将链表从中间分开,分成两个子链表,这里使用快慢指针找到中间节点位置
2、对两个子链表分别进行递归排序
3、将两个链表合并为一个有序链表
具体实现
那么这里我们如何使用快慢指针找到中间节点位置?
//使用快慢指针找到中间节点
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//中间节点
ListNode mid = slow.next;
1、定义两个指针 slow 和 fast,初始时都指向链表的头节点 head。
2、将 slow 指针每次向后移动一步,将 fast 指针每次向后移动两步,直到 fast 指针到达链表末尾。
3、此时 slow 指针所指的节点就是链表的中间节点。
为什么这种方法是正确的呢?因为 fast 指针每次移动的步数是 slow 指针的两倍,所以当 fast 指针到达链表末尾时,slow 指针刚好走到链表的中间位置。
需要注意的是,当链表长度为偶数时,有两个中间节点,这种情况下可以选择返回其中任意一个节点,本题选择返回中间位置靠左的节点。
如何递归?
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (left != null && right != null){
if (left.val < right.val){
tail.next = left;
left = left.next;
}else {
tail.next = right;
right = right.next;
}
tail = tail.next;
}
tail.next = left != null ? left : right;
return dummy.next;
其实这里就是归并排序的核心,我把一个数组从 8 分成了 4 在分成 2,那么最后这 2 ,是不是就是 left.val 和 right.val 了。重复上述操作,在合并两个子链表即可。
代码:
public static 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 mid = slow.next;
slow.next = null;
//递归对两个子链表进行排序
ListNode left = sortList(head);
ListNode right = sortList(mid);
//合并两个子链表
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (left != null && right != null){
if (left.val < right.val){
tail.next = left;
left = left.next;
}else {
tail.next = right;
right = right.next;
}
tail = tail.next;
}
tail.next = left != null ? left : right;
return dummy.next;
}