Sort a linked list in O(n log n) time using constant space complexity.
思路:归并排序
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (head == nullptr || head->next == nullptr){
return head;
}
ListNode* mid = MoveToMid(head);
head = MergeSort(head, mid);
return head;
}
ListNode* MoveToMid(ListNode* head){
ListNode *p1 = head, *p2 = head;
while (p1 != nullptr && (p2->next&&p2->next->next)){
p1 = p1->next;
p2 = p2->next->next;
}
if (p1 != nullptr){
ListNode*tmp = p1->next;
p1->next = nullptr;
//printList(tmp);
return tmp;
}
else
return nullptr;
}
ListNode* MergeSort(ListNode* list1, ListNode* list2){
if (list1 == nullptr&&list2 == nullptr)
return nullptr;
else if ((list1 == nullptr&&list2 != nullptr) ||
(list1 != nullptr&&list2 == nullptr))
{
return list1 == nullptr ? list2 : list1;
}
ListNode* mid1 = MoveToMid(list1);
ListNode* mid2 = MoveToMid(list2);
list1 = MergeSort(list1, mid1);
list2 = MergeSort(list2, mid2);
ListNode* pre = new ListNode(0);
ListNode* p = pre;
while (list1 != nullptr&&list2 != nullptr){
if (list1->val > list2->val){
p->next = list2;
p = p->next;
list2 = list2->next;
}
else{
p->next = list1;
p = p->next;
list1 = list1->next;
}
}
if (list1 != nullptr) p->next = list1;
else if (list2 != nullptr) p->next = list2;
else p->next = nullptr;
//printList(pre->next);
return pre->next;
delete pre;
}
}a;