import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        // 解题思路:
        // 3指针 left/mid/right
        // right=head.next.next 指针每次走2步,left=head 指针每次走一步
        // mid=head.next指针每次走一步
        // 当right指针为null时,mid在最中间,left 在mid前一个,把left.next 指为null 拆为2个链表
        // 然后开始递归合并2个链表
        if (head == null || head.next == null) {
            return head;
        }

        ListNode left = head;
        ListNode mid = head.next;
        ListNode right = head.next.next;

        while (right != null && right.next != null) {
            left = left.next;
            mid = mid.next;
            right = right.next.next;
        }

        left.next = null;

        return merge(sortInList(head), sortInList(mid));
    }

    private ListNode merge(ListNode n1, ListNode n2) {
        ListNode root = new ListNode(-1);
        ListNode cur = root;

        while (n1 != null || n2 != null) {
            if (n1 == null) {
                cur.next = n2;
                break;
            } else if (n2 == null) {
                cur.next = n1;
                break;
            } else {
                if (n1.val < n2.val) {
                    cur.next = n1;
                    n1 = n1.next;
                } else {
                    cur.next = n2;
                    n2 = n2.next;
                }
            }
            cur = cur.next;
        }

        return root.next;
    }


}