主要思路
自顶向下归并排序:
1.首先使用快慢指针法找中点拆分链表
2.对两个子链表分别排序
3.最后合并两个有序链表
class Solution {
public:
//找中点 拆分
ListNode *sortList(ListNode *head, ListNode *tail) {
if(head==nullptr)return head;
if(head->next == tail) {
head->next = nullptr;
return head;
}
//双指针找中点
ListNode *slow = head;
ListNode *fast = head;
while(fast!=tail&&fast->next!=tail) {
slow = slow->next;
fast = fast->next;
fast = fast->next;
}
ListNode *mid = slow;
return mergeTwoSortedLists(sortList(head,mid),sortList(mid,tail));
}
//合并两个有序链表
ListNode *mergeTwoSortedLists(ListNode *l1,ListNode *l2) {
if(l1==nullptr||l2==nullptr) return l1 ? l1 : l2;
ListNode *dummyNode = new ListNode(-1);
ListNode *cur = dummyNode;
while(l1!=nullptr&&l2!=nullptr) {
if(l1->val < l2->val) {
cur->next = l1;
l1 = l1 -> next;
}
else {
cur->next = l2;
l2 = l2->next;
}
cur = cur -> next;
}
cur ->next = (l1?l1:l2);
return dummyNode->next;
}
ListNode* sortList(ListNode* head) {
return sortList(head,nullptr);
}
};