力扣148. 排序链表

64 阅读1分钟

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

示例 1:

image.png

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

提示:

  • 链表中节点的数目在范围 [0, 5 * 104] 内
  • -105 <= Node.val <= 105

 

进阶: 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

class Solution {
    public ListNode sortList(ListNode head) {
        //1.定义快慢指针找到链表中间节点
        if(head == null || head.next == null){
            return head;
        }
        ListNode slow = head;
        ListNode fast = slow.next;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        //2.此时slow即为链表中间节点,沿中间节点将链表一分为二,在进行归并排序
        ListNode first = head;
        ListNode second = slow.next;
        //3.归并排序
        first  = sortList(first);
        second  = sortList(second);
        return mergeList(first,second);
    }
    ListNode mergeList(ListNode left,ListNode right){
        ListNode dummy = new ListNode();
        ListNode tail = dummy;
        while (right != null && left != null ){
            if(right.val > left.val){
                tail.next = left;
                left = left.next;
            }else {
                tail.next = right;
                right = right.next;
            }
            tail = tail.next;
        }
        if(left != null){
            tail.next = left;
        }else {
            tail.next = right;
        }
        return dummy.next;
    }
}