快慢指针+反转链表使得空间复杂度降到O(1):需要注意链表长度是奇数还是偶数的情况。

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 slow = head, fast = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        if(fast != null) {
            slow = slow.next;
        }
        fast = slow;
        slow = head;
        fast = rev(fast);
        while(slow != null && fast != null) {
            if(slow.val != fast.val) {
                return false;
            }
            slow = slow.next;
            fast = fast.next;
        } 
        return true;
    }
    
    public ListNode rev(ListNode node) {
        ListNode pre = node;
        ListNode cur = node.next;
        node.next = null; 
        while(cur != null) {
            ListNode p = cur.next;
            cur.next = pre;
            pre = cur;
            cur = p;
        }
        return pre;
    }
}