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
Accepted
173,715
Submissions
507,027
/**
* 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==NULL||head->next==NULL)
return head;
ListNode* fast = head;
ListNode* slow = head;
while(fast->next!=NULL&&fast->next->next!=NULL){
slow = slow->next;
fast = fast->next->next;
}
fast = slow;
slow = slow ->next;
fast->next =NULL;
ListNode *l1 = sortList(head);
ListNode *l2 = sortList(slow);
return MergeList(l1,l2);
}
ListNode *MergeList(ListNode* l1,ListNode* l2){
ListNode dummy(-1);
for (ListNode* p = &dummy; l1 != NULL || l2 != NULL; p = p->next)
{
int val1 = l1 == NULL ? INT_MAX : l1->val;
int val2 = l2 == NULL ? INT_MAX : l2->val;
if (val1 <= val2)
{
p->next = l1;
l1 = l1->next;
}
else
{
p->next = l2;
l2 = l2->next;
}
}
return dummy.next;
}
};
归并排序,找到中间结点,利用递归的归并排序进行合并