148. Sort List

mergeSort

 

 

 1 class Solution {
 2     public ListNode sortList(ListNode head) {
 3         if(head == null || head.next == null) return head;
 4         ListNode slow = head;
 5         ListNode fast = head;
 6         while(fast.next != null && fast.next.next != null){
 7             fast = fast.next.next;
 8             slow = slow.next;
 9         }
10         ListNode next = slow.next;  //要把中间的next = null 否则不会停止了
11         slow.next = null;
12        return merge(sortList(head), sortList(next));
13         
14     }
15     public ListNode merge(ListNode first, ListNode second){
16         if(first == null) return second;
17         if(second == null) return first;
18         ListNode dummy = new ListNode(0);
19         ListNode cur = dummy;
20         while(first != null && second != null){
21             if(first.val <= second.val){
22                 cur.next = first;
23                 first = first.next;
24                 cur = cur.next;
25             }else{
26                 cur.next = second;
27                 second = second.next;
28                 cur = cur.next;
29             }
30         }
31         if(first == null){
32             cur.next = second;
33         }else if(second == null){
34             cur.next = first;
35         }
36        
37         return dummy.next;      
38     }
39 }

 

posted @ 2018-10-30 11:20  jasoncool1  阅读(113)  评论(0)    收藏  举报