Leetcode -- Sort List

来源:互联网 发布:青少年使用网络调查 编辑:程序博客网 时间:2024/05/16 10:32

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

分析:
O(n log n)有归并排序,快速排序和堆排序。针对链表,采用归并排序是比较合理的。快排在最坏的情况,复杂度是O(n^2)。

思路:难点在于寻找链表的中点。

代码:

 ListNode* sortList(ListNode* head) {        //如果head是空的,或者只有一个node,就不需要排序了        if (head == NULL ||head -> next == NULL) return head;        //fast, slow配合寻找中点。        ListNode* fast = head;        ListNode* slow = head;        while(fast->next && fast->next->next)        {            slow = slow -> next;            fast = fast ->next->next;        }        fast = slow;        slow = fast -> next;        fast->next = NULL;        fast = sortList(head);        slow = sortList(slow);        return merge(fast, slow);    }    //将两个排好序的链表,合成一个。    ListNode* merge(ListNode* head1, ListNode* head2)    {        if(head1 == NULL) return head2;        if(head2 == NULL) return head1;        ListNode* l;        if(head1->val > head2 -> val)        {            l = head2;            head2 = head2->next;        }        else        {            l = head1;            head1= head1->next;        }        ListNode* l1 = l;        while(head1 && head2)        {            if(head1->val > head2 -> val)            {                l->next = head2;                head2 = head2 -> next;                l = l-> next;            }            else            {                l-> next = head1;                head1 = head1 -> next;                l = l->next;            }        }        if(head1)        {            l->next = head1;        }        if(head2)        {            l->next = head2;        }        return l1;    }
0 0