zoukankan      html  css  js  c++  java
  • 148. Sort List

    148. Sort List


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

    利用mergesort 

    merge 操作只能合并2个有序的子序列

    所以利用递归对每个子序列进行排序,排序后merge。

     1 class Solution {
     2     public ListNode sortList(ListNode head) {
     3         if(head==null || head.next==null) return head;
     4         
     5         //1 split 
     6         ListNode pre=null,slower =head,faster=head;
     7         while(faster!=null && faster.next!= null){
     8             pre = slower;
     9             slower = slower.next;
    10             faster = faster.next.next;
    11         }
    12         pre.next = null;
    13         //2 sort 
    14         ListNode l1 = sortList(head);
    15         ListNode l2 = sortList(slower);
    16         //3 merge
    17         return Merge(l1,l2);
    18         
    19     }
    20     
    21     public ListNode Merge(ListNode l1,ListNode l2){
    22         ListNode l ,p;
    23         l = new ListNode(0);
    24         p=l;
    25         
    26         while(l1 != null&& l2 != null){
    27             if(l1.val<l2.val){
    28                 p.next = l1;
    29                 l1 = l1.next;
    30             }
    31             else{
    32                 p.next = l2;
    33                 l2 = l2.next;
    34             }
    35             p = p.next;
    36         }
    37         if(l1==null) p.next = l2;
    38         if(l2==null) p.next = l1;
    39         return l.next;
    40     }
    41 }
  • 相关阅读:
    最近ACM刷题见到的没见过的名词
    最近刷题常常遇见的需要百度的知识点
    简单RPG场景实现(改
    简单RPG场景实现
    位图载入与位图移动
    动态菜单
    静态菜单
    双人五子棋
    HDU 2112 HDU Today
    音痴又音痴的LT
  • 原文地址:https://www.cnblogs.com/zle1992/p/7642937.html
Copyright © 2011-2022 走看看