链表:排序链表

103 阅读1分钟

leetcode:148. 排序链表

题目描述

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

示例

输入: head = [4,2,1,3]
输出: [1,2,3,4]

解题思路

归并排序 分治思路

  1. 递归 将链表划分为长度为1或0的子链表(有序)
    • 快慢指针 中间节点划分
  2. 两两合并有序链表

image.png

完整代码:

class Solution {
    public ListNode sortList(ListNode head) {
        if (null == head || null == head.next) {
            return head;
        }

        ListNode slow = head, fast = head.next;
        while (null != fast && null != fast.next) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode r = sortList(slow.next);
        slow.next = null;
        ListNode l = sortList(head);

        return mergeList(l, r);
    }

    ListNode mergeList(ListNode l, ListNode r) {
        ListNode dummy = new ListNode(-1);
        ListNode p = dummy;
        while (null != l && null != r) {
            if (l.val < r.val) {
                p.next = l;
                l = l.next;
            }
            else {
                p.next = r;
                r = r.next;
            }
            p = p.next;
        }
        p.next = null == l ? r : l;
        return dummy.next;
    }
}