234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?


(1)定义快慢指针得到链表的中点 (2)将后半部分逆序 (3)从头节点和中点开始比较是否相同

 public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode slow=head;
        ListNode fast=head;
        while (fast.next!=null&&fast.next.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        reverseList(slow.next);
        slow=head;
        while (fast!=null){
            if (fast.val!=slow.val)
                return false;
            fast=fast.next;
            slow=slow.next;
        }
        return true;
    }

    public ListNode reverseList(ListNode head) {
        if (head.next == null)
            return head;
        ListNode node = reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return node;
    }

  

加油啦!加油鸭,冲鸭!!!
原文地址:https://www.cnblogs.com/clarencezzh/p/10957034.html