LC.148.Sort List

https://leetcode.com/problems/sort-list/description/
Sort a linked list in O(n log n) time using constant space complexity.
找到中点之后的处理,和 143 "Reorder List" 是一样的 : 然后把tail 传后面去
ListNode tail = mid.next ;
//cut it off
mid.next = null ;

time: o(nlogn) space: o(n): recursive with n stacks
 1 public ListNode sortList(ListNode head) {
 2         if (head == null || head.next == null) return head ;
 3         //merge sort
 4         //find the mid,
 5         ListNode mid = getMid(head) ;
 6         ListNode tail = mid.next ;
 7         //cut it off
 8         mid.next = null ;
 9         //recursive
10         ListNode firstHead = sortList(head) ;
11         ListNode secHead = sortList(tail) ;
12         //merge: same logic as merge two sorted list
13          ListNode newHead = merge(firstHead, secHead);
14          return newHead;
15     }
16 
17     private ListNode merge(ListNode firstHead, ListNode secHead) {
18         ListNode dummy = new ListNode(0) ;
19         ListNode curr = dummy ;
20         while (firstHead != null && secHead != null){
21             if (firstHead.val<secHead.val){
22                 curr.next = firstHead ;
23                 firstHead = firstHead.next ;
24                 curr = curr.next ;
25             } else{
26                 curr.next = secHead ;
27                 secHead = secHead.next ;
28                 curr = curr.next ;
29             }
30         }
31         //corner case: either one side left
32         if (firstHead!=null){
33             curr.next = firstHead ;
34         }
35         if (secHead != null){
36             curr.next = secHead ;
37         }
38         return dummy.next ;
39     }
40 
41     private ListNode getMid(ListNode head){
42         if (head == null ) return head ;
43         ListNode fast = head , slow = head ;
44         while(fast != null && fast.next != null && fast.next.next != null){
45             fast = fast.next.next ;
46             slow = slow.next ;
47         }
48         return slow ;
49     }

 

posted @ 2018-02-26 06:19  davidnyc  阅读(158)  评论(0编辑  收藏  举报