148. Sort List--单链表自底向上归并排序

来源:互联网 发布:java微信公众开发项目 编辑:程序博客网 时间:2024/06/05 17:07

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

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode sortList(ListNode head) {        return merge(head);    }    public ListNode merge(ListNode head){    //用于不断细分链表,然后迭代返回合并得最终一个有序链表。        if(head == null || head.next == null)            return head;        ListNode middle = getMiddle(head);        ListNode second = middle.next;        middle.next = null;        return sorted(merge(head), merge(second));    }    public ListNode sorted(ListNode a, ListNode b){    //用于将两组排序好的链表合并成新的排序好的链表        if(a == null)            return b;        if(b == null)            return a;        if(a.val < b.val){            a.next = sorted(a.next, b);            return a;        }        else{            b.next = sorted(a, b.next);            return b;        }    }    public ListNode getMiddle(ListNode head){    //用于寻找链表中点        if(head == null)            return head;        ListNode slow = head;        ListNode fast = head;        while(fast.next != null && fast.next.next != null){            slow = slow.next;            fast = fast.next.next;        }        return slow;    }}