利用归并排序
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
//分开
//利用快慢指针找到中点
ListNode* slow = head, *fast = head->next;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode* temp = slow->next;
//切分开
slow->next = nullptr;
//递归切分
ListNode* left = sortList(head);
ListNode* right = sortList(temp);
ListNode* h = new ListNode();
ListNode* cur = h;
//合并
while(left && right){
if(left->val <= right->val){
cur->next = left;
left = left->next;
cur = cur->next;
}else{
cur->next = right;
right = right->next;
cur = cur->next;
}
}
if(left) cur->next = left;
if(right) cur->next = right;
// cur = h->next;
// delete h;
return h->next;
}
};