码迷,mamicode.com
首页 > 编程语言 > 详细

45.Sort List(链表排序)

时间:2019-06-25 00:28:46      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:next   head   log   link   fast   java   output   slow   思路   

Level:

??Medium

题目描述:

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

思路分析:

??对链表进行归并排序,时间复杂为O(nlgn),空间复杂度为O(1)。

代码:

public class Solution{
    public ListNode sortList(ListNode head){
        if(head==null||head.next=null)
            return head;
        ListNode slow=head;
        ListNode fast=head;
        while(fast.next!=null&&fast.next.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        ListNode right=slow.next;
        slow.next=null;//将左右链表断开
        return merge(sortList(head),sortList(right));
    }
    public ListNode merge(ListNode head,ListNode right){
        if(head==null)
            return right;
        if(right==null)
            return head;
        ListNode pHead=new ListNode(0);
        if(head.val<right.val){
            pHead=head;
            pHead.next=merge(head.next,right);
        }else{
            pHead=right;
            pHead.next=merge(head,right.next);
        }
        return pHead;
    }
}

45.Sort List(链表排序)

标签:next   head   log   link   fast   java   output   slow   思路   

原文地址:https://www.cnblogs.com/yjxyy/p/11080420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!