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
看到时间复杂度为logn,一般联想到归并排序,要形成条件反射(logn是个很特别的时间复杂度,一般出现对半分的时候时间复杂度才会出现log)。
归并排序:合并两个有序链表。sortList的功能是返回一个有序的链表。Merge的功能是合并两个有序链表。
/**
* 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) {
ListNode *temp1;
ListNode *temp2;
if(!head||!head->next)
return head;
ListNode *slow = head;
ListNode *fast = head->next->next;
while(fast&&fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* temp = slow->next;
slow->next = NULL;
return Merge(sortList(head),sortList(temp));
}
ListNode* Merge(ListNode* head,ListNode* second)
{
if(!head)
return second;
if(!second)
return head;
ListNode* phead;
if(head->val<second->val)
{
phead = head;
phead->next = Merge(head->next,second);
return phead;
}
else
{
phead = second;
phead->next = Merge(head,second->next);
return phead;
}
}
};