import java.util.*;

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

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode sortLinkedList (ListNode head) {
        // write code here
        // 解题思路:遍历链表,取出来奇数链表和偶数链表
        // 对偶数链表反转
        // 合并2个链表
        if (head == null) {
            return null;
        }

        ListNode q = new ListNode(0);
        ListNode o = new ListNode(0);
        ListNode curQ = q;
        ListNode curO = o;
        int i = 1;

        while (head != null) {
            if (i % 2 == 0) {
                curO.next = new ListNode(head.val);
                curO = curO.next;
            } else {
                curQ.next = new ListNode(head.val);
                curQ = curQ.next;
            }
            i++;
            head = head.next;
        }

        ListNode reO = resever(o.next);
        curQ = q.next;
        ListNode root = new ListNode(0);
        ListNode cur = root;

        while (reO != null || curQ != null) {
            int valO = (reO == null) ? Integer.MAX_VALUE : reO.val;
            int valQ = (curQ == null) ? Integer.MAX_VALUE : curQ.val;

            if (valO > valQ) {
                cur.next = new ListNode(valQ);
                curQ = curQ.next;
            } else {
                cur.next = new ListNode(valO);
                reO = reO.next;
            }

            cur = cur.next;
        }

        return root.next;
    }

    private ListNode resever(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode pre = null;
        ListNode next;

        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }

        return pre;
    }
}