45.Sort List (list sorting)

Level:

  Medium

Subject description:

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

Analysis of ideas:

  Linked list of merge sort, time complexity is, the space complexity of O (nlgn) to O (1).

Code:

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;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11080420.html