/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* split(ListNode* head) {
ListNode *slow = head, *fast = head->next;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* mid = slow->next;
slow->next = nullptr;
return mid;
}
ListNode* merge(ListNode* head1, ListNode* head2) {
ListNode *preHead = new ListNode(0), *node = preHead;
while (head1 != nullptr && head2 != nullptr) {
if (head1->val < head2->val) {
node->next = head1;
head1 = head1->next;
} else {
node->next = head2;
head2 = head2->next;
}
node = node->next;
}
if (head1 != nullptr) node->next = head1;
if (head2 != nullptr) node->next = head2;
return preHead->next;
}
ListNode* sortList(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* subHead1 = head;
ListNode* subHead2 = split(head);
subHead1 = sortList(subHead1);
subHead2 = sortList(subHead2);
return merge(subHead1, subHead2);
}
};