[leetcode]Sort List

Sort List

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

 

算法思想:

时间复杂度为O(nlogn)的排序算法,有快排、归并、堆排序,快排需要往前遍历,因此不适合单链表,堆排序可以,但是需要O(n)的空间,因此本题的最佳答案应该是归并排序。

与Array的merge sort思想完全一致。

代码如下:

 1 public class Solution {
 2  public ListNode sortList(ListNode head) {
 3         if(head == null || head.next == null) return head;
 4         ListNode hhead = new ListNode(0);
 5         hhead.next = head;
 6         ListNode fast = hhead;
 7         ListNode slow = hhead;
 8         while(fast != null && fast.next != null){
 9             fast = fast.next.next;
10             slow = slow.next;
11         }
12         ListNode right = slow.next;
13         slow.next = null;
14         ListNode left = sortList(head);
15         right = sortList(right);
16         return merge(left, right);
17     }
18     private ListNode merge(ListNode l1,ListNode l2){
19         ListNode hhead = new ListNode(0);
20         hhead.next = l1;
21         ListNode p = hhead;
22         while(p.next != null){
23             if(p.next.val > l2.val){
24                 ListNode tem = l2;
25                 l2 = l2.next;
26                 tem.next = p.next;
27                 p.next = tem;
28             }else
29                 p = p.next;
30                 if(l2 == null) return hhead.next;
31             }
32         p.next = l2;
33         return hhead.next;
34         }
35 }

 

posted on 2014-07-21 22:33  喵星人与汪星人  阅读(258)  评论(0编辑  收藏  举报