/**
* 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* findMiddle(ListNode* head) {
ListNode* fast = head;
ListNode* slow = nullptr;
while(fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = (slow == nullptr) ? head : slow->next;
}
ListNode* mid = slow->next;
slow->next = nullptr;
return mid;
}
ListNode* merge(ListNode* left, ListNode* right) {
ListNode* dummy = new ListNode(-1);
ListNode* curr = dummy;
while(left != nullptr && right != nullptr) {
if(left->val < right->val) {
curr->next = left;
left = left->next;
} else {
curr->next = right;
right = right->next;
}
curr = curr->next;
}
if(left != nullptr) {
curr->next = left;
} else {
curr->next = right;
}
return dummy->next;
}
ListNode* sortList(ListNode* head) {
if(head == nullptr) return nullptr;
if(head->next == nullptr) return head;
ListNode* mid = findMiddle(head);
ListNode* left = sortList(head);
ListNode* right = sortList(mid);
return merge(left, right);
}
};