首页 > 其他 > 详细

148. Sort List

时间:2017-10-25 16:24:21      阅读:272      评论:0      收藏:0      [点我收藏+]

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

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

思路:使用归并排序

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

 

148. Sort List

原文:http://www.cnblogs.com/wzj4858/p/7729381.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!