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 oddEvenList (ListNode head) {
        // write code here
        // 1.处理特殊情况
        if (head == null || head.next == null) {
            return  head;
        }
        // 2. 定义所需链表头与尾指针
        ListNode bs = null;
        ListNode be = null;
        ListNode as = null;
        ListNode ae = null;

        // 3. 遍历jinx处理
        int index = 1;
        while (head != null) {
            if (index % 2 == 0) {
                // 3.2 如果是偶数节点则在后一段链表
                if (as == null) {
                    // 3.2.1 如果是第一次插入,则进行处理
                    as = head;
                    ae = head;
                } else {
                    // 3.2.2 链表尾插法
                    ae.next = head;
                    ae = ae.next;
                }
            } else {
                // 3.3 如果是奇数节点则在前一段
                if (bs == null) {
                    // 3.3.1 链表尾插法
                    bs = head;
                    be = head;
                } else {
                    be.next = head;
                    be = be.next;
                }
            }
            head = head.next;
            index++;
        }

        // 4. 防止奇数个节点导致循环链表
        ae.next = null;
        // 5. 连接奇链表与偶链表
        be.next = as;
        return bs;
    }
}