148. Sort List

来源:互联网 发布:阿里云系统与安卓区别 编辑:程序博客网 时间:2024/05/17 21:39

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

思路:可以参考归并排序的思想,一半一半的使之有序,然后归并

代码如下(已通过leetcode)

public class Solution {
   public ListNode sortList(ListNode head) {
    if(head==null||head.next==null) return head;
    ListNode middle=getmiddle(head);
    ListNode next=middle.next;
    middle.next=null;
    return mergeList(sortList(head),sortList(next));
   }
   
   public ListNode getmiddle(ListNode head) {
    ListNode slow=head;
    ListNode fast=head;
    while(fast.next!=null&&fast.next.next!=null) {
    slow=slow.next;
    fast=fast.next.next;
    }
    return slow;
   }
   
   public ListNode mergeList(ListNode head1,ListNode head2) {
    ListNode res=new ListNode(-1);
    ListNode cur=res;
    while(head1!=null&&head2!=null) {
    if(head1.val<head2.val) {
    cur.next=head1;
    head1=head1.next;
    } else {
    cur.next=head2;
    head2=head2.next;
    }
    cur=cur.next;
    }
    while(head1!=null) {
    cur.next=head1;
    head1=head1.next;
    cur=cur.next;
    }
    while(head2!=null) {
    cur.next=head2;
    head2=head2.next;
    cur=cur.next;
    }
    return res.next;
   
   }
}

0 0