天天看点

【LeetCode】Sort List 解题报告(对链表进行归并排序)

【题目】

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

【归并排序】

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null) return null;
        
        // only one node
        if (head.next == null) return head;
        
        // only two nodes
        if (head.next.next == null) {
            if (head.val <= head.next.val) {
                return head;
            } else {
                ListNode newhead = head.next;
                head.next.next = head;
                head.next = null;
                return newhead;
            }
        }
        
        // more than three nodes
        // divide the list two parts
        ListNode f = head, s = head;
        while (f != null && f.next != null) {
            f = f.next.next;
            s = s.next;
        }
        ListNode m = s.next;
        s.next = null; // make the first part end
        
        // sort the two parts individually
        ListNode n1 = sortList(head);
        ListNode n2 = sortList(m);
        
        // find the new head afther merge
        ListNode newhead;
        if (n1.val <= n2.val) {
            newhead = n1;
            n1 = n1.next;
        } else {
            newhead = n2;
            n2 = n2.next;
        }
        
        // merge the two sorted parts
        ListNode n3 = newhead;
        while (n1 != null && n2 != null) {
            if (n1.val <= n2.val) {
                n3.next = n1;
                n3 = n3.next;
                n1 = n1.next;
            } else {
                n3.next = n2;
                n3 = n3.next;
                n2 = n2.next;
            }
        }
        if (n1 != null) {
            n3.next = n1;
        }
        if (n2 != null ) {
            n3.next = n2;
        }
        
        return newhead;
    }
}
           

这道题竟然一遍AC了,不过想想也是,很基础的算法,这只能说明对归并排序和链表基本操作比较熟练了。