Sort a linked list in O(n log n) time using constant space complexity.
记得Insert Sort List, 那个复杂度是O(N^2)的,这里要求O(nlogn),所以想到merge sort, 需要用到Merge Two Sorted List的方法(我写的merge函数)
第二遍代码:所以mergesort不好写在于它是一个递归里嵌套另一个递归,第一个递归不停地用runner technique把list分两段,直到每一段是一个或0个节点返回该点,这时再调用merge Two sorted List递归把两段整合起来,返回它们的首节点
1 public class Solution { 2 public ListNode sortList(ListNode head) { 3 if (head == null || head.next == null) return head; 4 return mergesort(head); 5 } 6 7 public ListNode mergesort(ListNode head) { 8 if (head == null || head.next == null) return head; 9 ListNode dummy = new ListNode(-1); 10 dummy.next = head; 11 ListNode walker = dummy; 12 ListNode runner = dummy; 13 while (runner!=null && runner.next!=null) { 14 runner = runner.next.next; 15 walker = walker.next; 16 } 17 ListNode head1 = dummy.next; 18 ListNode head2 = walker.next; 19 walker.next = null; 20 return merge(mergesort(head1), mergesort(head2)); 21 } 22 23 public ListNode merge(ListNode head1, ListNode head2) { 24 if (head1 == null) return head2; 25 if (head2 == null) return head1; 26 ListNode dummy = new ListNode(-1); 27 dummy.next = head1; 28 ListNode pre = dummy; 29 while (head1 != null && head2 != null) { 30 if (head1.val <= head2.val) { 31 head1 = head1.next; 32 } 33 else { 34 ListNode next = head2.next; 35 head2.next = pre.next; 36 pre.next = head2; 37 head2 = next; 38 } 39 pre = pre.next; 40 } 41 if (head2 != null) { 42 pre.next = head2; 43 } 44 return dummy.next; 45 } 46 }