Sort List

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

思路:使用O(nlogn)时间复杂度和常数空间复杂度,我们想到可以用归并排序。

1)找到链表中间位置

2)将两个链表按序合并链表

3)对所给链表进行整体的归并排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
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;
    }
    ListNode *Merge(ListNode *head1,ListNode *head2)
    {
        ListNode *dummy=new ListNode(-1);
        ListNode *cur=dummy;
        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 dummy->next;
    }
    ListNode *sortList(ListNode *head) {
        if(head==NULL||head->next==NULL)
            return head;
        ListNode *mid=getMiddle(head);
        ListNode *pHead2=mid->next;
        mid->next=NULL;
        return Merge(sortList(head),sortList(pHead2));
    }
};

 

posted @ 2014-06-25 10:40  Awy  阅读(149)  评论(0编辑  收藏  举报