🌗 148. 排序链表
2022年10月10日
- algorithm
🌗 148. 排序链表
难度: 🌗
问题描述
解法
/**
* 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) {
// 思路:
// 归并排序 - 快慢指针找中点
return mySol(head);
}
private ListNode mySol(ListNode head) {
// 递归终止条件
if(head == null || head.next == null) {
return head;
}
// 至少 2 个节点
ListNode prev = getMid(head);
ListNode left = head;
ListNode right = prev.next;
prev.next = null;
ListNode a = mySol(left);
ListNode b = mySol(right);
return merge(a, b);
}
private ListNode merge(ListNode left, ListNode right) {
ListNode res = new ListNode(-1);
ListNode cur = res;
while(left != null && right != null) {
if(left.val <= right.val) {
cur.next = left;
left = left.next;
cur = cur.next;
} else {
cur.next = right;
right = right.next;
cur = cur.next;
}
}
while(left != null) {
cur.next = left;
left = left.next;
cur = cur.next;
}
while(right != null) {
cur.next = right;
right = right.next;
cur = cur.next;
}
return res.next;
}
private ListNode getMid(ListNode head) {
// 找到链表偏左的那个中点的前一个节点,方便后续拆分
ListNode slow = head;
ListNode prev = head;
ListNode fast = head.next;
while(fast != null && fast.next != null) {
fast = fast.next.next;
prev = slow;
slow = slow.next;
}
return prev;
}
}