/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cerrno>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        if(head->next==nullptr)
            return head;

        return MergeSortList(head);
    }
    ListNode* MergeSortList(ListNode* head)
    {
        if(head==nullptr||head->next==nullptr)
            return head;

        ListNode* fast=head->next;
        ListNode* slow=head;

        while(fast!=nullptr&&fast->next!=nullptr)
        {
            fast=fast->next->next;
            slow=slow->next;
        }

        ListNode* mid=slow->next;
        slow->next=nullptr;

        ListNode* Left=MergeSortList(head);
        ListNode* Right=MergeSortList(mid);

        return Merge(Left,Right);
    }
    ListNode* Merge(ListNode* Left,ListNode* Right)
    {
        ListNode* p=new ListNode(-1);
        ListNode* ptr=p;

        while(Left!=nullptr&&Right!=nullptr)
        {
            if(Left->val<Right->val)
            {
                ptr->next=Left;
                ptr=ptr->next;
                Left=Left->next;
            }
            else
            {
                ptr->next=Right;
                ptr=ptr->next;
                Right=Right->next;
            }
        }
        if(Left!=nullptr)
            ptr->next=Left;
        else
            ptr->next=Right;
        return p->next;
    }
};