给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
思路:
最适合链表的排序方式就是归并排序,把链表从中间切开,两边分别排序再合并有序链表。操作分为三步:
1.拆分(cut)
2.排序(sort)
3.合并(merge)
class Solution {
public:
ListNode* sortList(ListNode* head) {
return sortList(head, nullptr);
}
ListNode* sortList(ListNode* start, ListNode* end)
{
if (!start) return nullptr;
if (start->next == end)
{
start->next = nullptr;
return start;
}
ListNode* fast = start;
ListNode* slow = start;
while(fast != end && fast->next != end)
{
fast = fast->next->next;
slow = slow->next;
}
ListNode* mid = slow;
ListNode* left = sortList(start, mid);
ListNode* right = sortList(mid, end);
ListNode* res = merge(left, right);
return res;
}
ListNode* merge(ListNode* l1, ListNode* l2)
{
if (l1 == nullptr) return l2;
if (l2 == nullptr) return l1;
ListNode* dummy = new ListNode;
ListNode* p = dummy;
ListNode* p1 = l1;
ListNode* p2 = l2;
while(p1 != nullptr && p2 != nullptr)
{
if (p1->val < p2->val)
{
p->next = new ListNode(p1->val);
p = p->next;
p1 = p1->next;
}
else
{
p->next = new ListNode(p2->val);
p = p->next;
p2 = p2->next;
}
}
if (p1 != nullptr)
{
p->next = p1;
}
else
{
p->next = p2;
}
return dummy->next;
}
};