import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    // 判断链表是否回文,反转一半链表,并进行比对!
    
    public boolean isPail (ListNode head) {
        // write code here
        if(head == null || head.next == null) return true;
        ListNode mid = getMid(head); // mid 的长度一定<= head,且长度差不超过 1;
        mid = reverse(mid);
        while(mid != null){
            if(mid.val != head.val) return false;
            mid = mid.next;
            head = head.next;
        }
        return true;
    }
    
    private ListNode getMid(ListNode head){
        if(head == null) return null;
        ListNode fake_head = new ListNode(-1);
        fake_head.next = head;
        ListNode pre = fake_head,slow = head,fast = head;
        
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
            pre = pre.next;
            if(fast != null) fast = fast.next;
        }
        pre.next = null;
        return slow;
    }
    
    private ListNode reverse(ListNode head){
        if(head == null || head.next == null) return head;
        ListNode next = head.next;
        ListNode reHead = reverse(head.next);
        next.next = head;
        head.next = null;
        return reHead;
    }
    
}