148. Sort List - Medium
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
divide and conquer + merge sort,先找中点,断开,再merge
time: O(nlogn), space: O(1)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null) return head; ListNode mid = getMiddle(head); ListNode second = mid.next; mid.next = null; return merge(sortList(head), sortList(second)); } private ListNode getMiddle(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; } private ListNode merge(ListNode n1, ListNode n2) { ListNode dummy = new ListNode(-1); ListNode cur = dummy; while(n1 != null && n2 != null) { if(n1.val <= n2.val) { cur.next = n1; n1 = n1.next; } else { cur.next = n2; n2 = n2.next; } cur = cur.next; } if(n1 != null) cur.next = n1; if(n2 != null) cur.next = n2; return dummy.next; } }