234. Palindrome Linked List

    /*
     * 234. Palindrome Linked List
     * 2016-6-15
     * 这里需要注意的地方就是count开始一定要设为0,然后要判断只有两个值的情况。这个方法很好只有constant的space
     * 还有一个问题就是:奇数个数跟偶数个数要区别对待!!!!
     * count的值也不同
     */
    public static boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null)
            return true;
        ListNode slow = head;
        ListNode fast = head;
        int count = 0;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            count++;
        }
        ListNode l1 = null;
        ListNode l2 = null;
        l1 = head;
        if (fast.next == null) {
            l2 = slow.next;
            slow.next = null;
        } else {
            count++;
            l2 = slow.next;
            slow.next = null;
        }
        ListNode ll2 = reverseList(l2);
        while (count != 0) {
            count--;
            if (ll2.val != l1.val) {
                return false;
            }
            l1 = l1.next;
            ll2 = ll2.next;
        }
        return true;
    }
原文地址:https://www.cnblogs.com/zmyvszk/p/5589712.html