首页 > 代码库 > [LeetCode] 148. Sort List

[LeetCode] 148. Sort List

https://leetcode.com/problems/sort-list/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode mid = findMiddle(head);
        ListNode head2 = sortList(mid.next);
        mid.next = null;
        ListNode head1 = sortList(head);
        return merge(head1, head2);
    }
    
    public ListNode merge(ListNode head1, ListNode head2) {
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        while (head1 != null && head2 != null) {
            if (head1.val < head2.val) {
                head.next = head1;
                head1 = head1.next;
            } else {
                head.next = head2;
                head2 = head2.next;
            }
            head = head.next;
        }
        while (head1 != null) {
            head.next = head1;
            head1 = head1.next;
            head = head.next;
        }
        while (head2 != null) {
            head.next = head2;
            head2 = head2.next;
            head = head.next;
        }
        return dummy.next;
    }
    
    public ListNode findMiddle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

 

[LeetCode] 148. Sort List