LC.148.Sort List

https://leetcode.com/problems/sort-list/description/
Sort a linked list in O(n log n) time using constant space complexity.
找到中点之后的处理,和 143 "Reorder List" 是一样的 : 然后把tail 传后面去
ListNode tail = mid.next ;
//cut it off
mid.next = null ;

time: o(nlogn) space: o(n): recursive with n stacks
 1 public ListNode sortList(ListNode head) {
 2         if (head == null || head.next == null) return head ;
 3         //merge sort
 4         //find the mid,
 5         ListNode mid = getMid(head) ;
 6         ListNode tail = mid.next ;
 7         //cut it off
 8         mid.next = null ;
 9         //recursive
10         ListNode firstHead = sortList(head) ;
11         ListNode secHead = sortList(tail) ;
12         //merge: same logic as merge two sorted list
13          ListNode newHead = merge(firstHead, secHead);
14          return newHead;
15     }
16 
17     private ListNode merge(ListNode firstHead, ListNode secHead) {
18         ListNode dummy = new ListNode(0) ;
19         ListNode curr = dummy ;
20         while (firstHead != null && secHead != null){
21             if (firstHead.val<secHead.val){
22                 curr.next = firstHead ;
23                 firstHead = firstHead.next ;
24                 curr = curr.next ;
25             } else{
26                 curr.next = secHead ;
27                 secHead = secHead.next ;
28                 curr = curr.next ;
29             }
30         }
31         //corner case: either one side left
32         if (firstHead!=null){
33             curr.next = firstHead ;
34         }
35         if (secHead != null){
36             curr.next = secHead ;
37         }
38         return dummy.next ;
39     }
40 
41     private ListNode getMid(ListNode head){
42         if (head == null ) return head ;
43         ListNode fast = head , slow = head ;
44         while(fast != null && fast.next != null && fast.next.next != null){
45             fast = fast.next.next ;
46             slow = slow.next ;
47         }
48         return slow ;
49     }

 

转载于:https://www.cnblogs.com/davidnyc/p/8471352.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值