题目要求:
Sort a linked list in O(n log n) time using constant space complexity.
满足O(n log n)时间复杂度的有快排、归并排序、堆排序。在这里采用的是归并排序(空间复杂度O(log n)),具体程序如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2)
{
ListNode *dummy = new ListNode();
ListNode *head = nullptr, *start = dummy;
while(l1 && l2)
{
if(l1->val < l2->val)
{
start->next = l1;
l1 = l1->next;
}
else
{
start->next = l2;
l2 = l2->next;
}
start = start->next;
} if(!l1)
start->next = l2;
else if(!l2)
start->next = l1; head = dummy->next;
delete dummy;
dummy = nullptr; return head;
} ListNode* mergeSort(ListNode* head)
{
if(!head->next)
return head; ListNode *slow = head, *fast = head;
ListNode *preNode = slow;
while(fast && fast->next)
{
preNode = slow;
slow = slow->next;
fast = fast->next->next;
}
preNode->next = nullptr; ListNode *left = mergeSort(head);
ListNode *right = mergeSort(slow);
return merge(left, right);
} ListNode* sortList(ListNode* head) {
if(!head || !head->next)
return head; return mergeSort(head);
}
};