Sort List

 1 public class Solution {
 2     public ListNode sortList(ListNode head) {
 3         if(head==null || head.next==null) return head;
 4         ListNode fast = head, slow = head;
 5         while(true){
 6             fast = fast.next;
 7             if(fast==null) break;
 8             fast = fast.next;
 9             if(fast==null) break;
10             slow = slow.next;
11         }
12         ListNode newHead = slow.next;
13         slow.next = null;
14         return merge(sortList(head),sortList(newHead));
15     }
16     public ListNode merge(ListNode p1,ListNode p2){
17         ListNode safe = new ListNode(-1);
18         ListNode p3 = safe;
19         while(p1!=null && p2!=null){
20             if(p1.val>p2.val){
21                 p3.next = p2;
22                 p2 = p2.next;
23             }
24             else{
25                 p3.next = p1;
26                 p1 = p1.next;
27             }
28             p3 = p3.next;
29         }
30         p3.next =p1==null?p2:p1;
31         return safe.next;
32     }
33 }
View Code

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

posted @ 2014-02-24 04:50  krunning  阅读(149)  评论(0编辑  收藏  举报