Leetcode: Sort List

来源:互联网 发布:学软件开发工资待遇 编辑:程序博客网 时间:2024/05/18 04:01

Sort List

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

解析:

由于要求时间复杂度为O(n log n),空间复杂度为O(n),使用分治类的排序算法才能符合要求。这里采取的是归并排序,运用递归将原始链表进行分割,然后再把子链表依次按顺序合并,实现排序目的。

代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode sortList(ListNode head) {        return Split(head);    }        private ListNode Split(ListNode head1)    {        if(head1==null||head1.next==null)return head1;                ListNode fast = head1;        ListNode slow = head1;        while(fast.next!=null && fast.next.next!=null)        {slow=slow.next;fast=fast.next.next;}                ListNode head2 = slow.next;        slow.next = null;        return Merge(Split(head1),Split(head2));    }        private ListNode Merge(ListNode n1, ListNode n2)    {        ListNode dummy = new ListNode(0);        ListNode pre = dummy;        while(n1!=null && n2!=null)        {            if(n1.val<n2.val)            {pre.next=n1;n1=n1.next;}            else            {pre.next=n2;n2=n2.next;}            pre = pre.next;        }        if(n1==null)pre.next = n2;        if(n2==null)pre.next = n1;        return dummy.next;    }}


0 0