LeetCode:链表排序

Sort a linked list in O(n log n) time using constant space complexity.

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

        ListNode midNode = findMid(head);
        ListNode right = midNode.next;
        midNode.next = null;

        ListNode left = sortList(head);
        right = sortList(right);

        return merge(left, right);
    }

    public ListNode findMid(ListNode head) {
        ListNode slow = head;
        ListNode fast = head.next;

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

        return slow;
    }

    public ListNode merge(ListNode head1, ListNode head2) {
        ListNode dummy = new ListNode(0);//为了方便cur的移动
        ListNode cur = dummy;

        while (head1 != null & head2 != null) {
            if (head1.val < head2.val) {
                cur.next = head1;
                head1 = head1.next;
            } else {
                cur.next = head2;
                head2 = head2.next;
            }
            cur = cur.next;
        }

        if (head1 != null) {
            cur.next = head1;
        }
        if (head2 != null) {
            cur.next = head2;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        Solution solution = new Solution();
        solution.sortList(head);
    }
}
原文地址:https://www.cnblogs.com/googlemeoften/p/5818241.html