148. Sort List

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

使用归并排序可以达到时间复杂度的要求。

首先将链表切分为两段,在进行归并排序。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode* pre=head;
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast&&fast->next)
        {
            pre=slow;
            fast=fast->next->next;
            slow=slow->next;
        }
        pre->next=NULL;
        return merge(sortList(head),sortList(slow));
    }
    ListNode* merge(ListNode* head1,ListNode* head2)
    {
        if(!head1) return head2;
        if(!head2) return head1;
        if(head1->val<head2->val)
        {
            head1->next=merge(head1->next,head2);
            return head1;
        }
        else
        {
            head2->next=merge(head1,head2->next);
            return head2;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/jifeng7288/article/details/79670380