class Solution {
public:
ListNode* merge(ListNode* a, ListNode* b) {
if (a == NULL) {
return b;
}
if (b == NULL) {
return a;
}
ListNode* new_head = NULL;
ListNode* cur = NULL;
if (a->val <= b->val) {
new_head = a;
a = a->next;
} else {
new_head = b;
b = b->next;
}
cur = new_head;
while(a && b) {
if (a->val <= b->val) {
cur->next = a;
cur = a;
a = a->next;
} else {
cur->next = b;
cur = b;
b = b->next;
}
}
if(a) {
cur->next = a;
}
if (b) {
cur->next = b;
}
return new_head;
}
ListNode* sortList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* first = head;
ListNode* mid = getMid(head);
ListNode* second = mid->next;
mid->next = NULL;
first = sortList(first);
second = sortList(second);
return merge(first, second);
}
ListNode* getMid(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head->next;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};