/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        // write code here
        ListNode* ResHead=recursion(head);
        return ResHead;
    }
  //将两个链表拆分再递归排序最后合并
    ListNode* recursion(ListNode* head){
        if(!head) return head;
        if(head&& !head->next) return head;
        auto right=head;
        ListNode* left;
        auto mid=head;
        while(right){
            right=right->next;
            left=mid;
            mid=mid->next;
            if(right) right=right->next;
            else break;
        }
        auto temp=left->next;
        left->next=nullptr;
        auto head1=recursion(head);
        ListNode* head2=recursion(temp);
        // printList(head1);
        // printList(head2);
        return Merge(head1,head2);
    }
    //对两个链表进行排序
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        // write code here
        if(pHead1==nullptr)
            return pHead2;
        if(pHead2==nullptr)
            return pHead1;
        ListNode* head=new ListNode(0);
        ListNode* firstPtr=pHead1;
        ListNode* secondPtr=pHead2;
        ListNode* currentPtr=head;
        while(firstPtr !=nullptr && secondPtr !=nullptr)
        {
            if(firstPtr->val<=secondPtr->val)
            {
                ListNode* temp1Ptr=firstPtr->next;
                firstPtr->next=nullptr;
                currentPtr->next=firstPtr;
                firstPtr=temp1Ptr;
                currentPtr=currentPtr->next;
            }
            else {
                ListNode* temp2Ptr=secondPtr->next;
                secondPtr->next=nullptr;
                currentPtr->next=secondPtr;
                secondPtr=temp2Ptr;
                currentPtr=currentPtr->next;
            }
            
        }
        if(firstPtr==nullptr&& secondPtr!=nullptr){
            currentPtr->next=secondPtr;
        }
        if(secondPtr==nullptr&& firstPtr!=nullptr) {
            currentPtr->next=firstPtr;
        }
        auto temp=head->next;
        head->next=nullptr;
        delete head;
        return temp;
    }
  //打印链表
    void printList(ListNode* head) {
        while (head != nullptr) {
            std::cout << head->val << " ";
            head = head->next;
        }
        std::cout << std::endl;
    }
};