/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* mid = getMid(head);
ListNode *left = sortInList(head);
ListNode *right = sortInList(mid);
return Merge(left, right);
}
ListNode* getMid(ListNode* head) {
if(!head) {
return head;
}
ListNode* fast = head, *slow = head;
ListNode* prev = slow;
while(fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = nullptr; // 切断mid和之前的联系,mid属于后面
return slow;
}
ListNode *Merge(ListNode *l1, ListNode *l2) {
if (!l1) {
l2;
}
if (!l2) {
l1;
}
ListNode *head = new ListNode(-1);
ListNode *ret = head;
while(l1 && l2) {
if (l1->val < l2->val) {
ret->next = new ListNode(l1->val);
l1 = l1->next;
} else {
ret->next = new ListNode(l2->val);
l2 = l2->next;
}
ret = ret->next;
}
if (l1) {
ret->next = l1;
}
if (l2) {
ret->next = l2;
}
return head->next;
}
};