148. Sort List

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

含义:为一个列表排序,要求空间复杂度为常量

思路:使用归并排序

 

 1 public class Solution {
 2     public ListNode sortList(ListNode head) {
 3         if (head == null || head.next == null) return head;
 4         ListNode slow = head, fast = head, pre = head;
 5         while (fast != null && fast.next != null) {
 6             pre = slow;
 7             slow = slow.next;
 8             fast = fast.next.next;
 9         }
10         pre.next = null;
11         return merge(sortList(head), sortList(slow));
12     }
13     public ListNode merge(ListNode l1, ListNode l2) {
14         ListNode dummy = new ListNode(-1);
15         ListNode cur = dummy;
16         while (l1 != null && l2 != null) {
17             if (l1.val < l2.val) {
18                 cur.next = l1;
19                 l1 = l1.next;
20             } else {
21                 cur.next = l2;
22                 l2 = l2.next;
23             }
24             cur = cur.next;
25         }
26         if (l1 != null) cur.next = l1;
27         if (l2 != null) cur.next = l2;
28         return dummy.next;
29     }
30 }

 

posted @ 2017-10-25 16:03  daniel456  阅读(84)  评论(0编辑  收藏  举报