# Palindrome Linked List

[https://leetcode.com/problems/palindrome-linked-list/description/](https://leetcode.com/problems/palindrome-linked-list/description/)

> Given a singly linked list, determine if it is a palindrome.
>
> Follow up:
>
> Could you do it in O(n) time and O(1) space?

## Thoughts

1. 把中间往后的整个翻转。这样就能同时从两头向中间遍历。不相等时则不是。
2. 找中点有个诀窍，类似Floyd检测环，一快一慢同时走，当快的停下来时慢的就是中点。这里我们特意让list长度时为奇数时，让右边的起始为中点的下一个。
3. reverse时会通过修改next置为prior == NULL把右边的和左边的切断。但左边还是和右边连着的。因此一一比对时条件应当是r != NULL. 因为l长度和r一样或多一个，因此遍历时也不会出现l和r中只有一个是null的情况。

## Code

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        auto m = mid(head);
        auto l = head, r = reverse(m);
        // r在reverse时next和前面的已经断了，因此用r作判断。
        while (r != NULL) {
            if (l->val != r->val) return false;
            l = l->next;
            r = r->next;
        }

        return true;
    }

private:
    ListNode* mid(ListNode *head) {
        auto slow = head, fast = head;
        while (fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        if (fast != NULL) slow = slow->next; // odd nodes: let right half smaller
        return slow;
    }

    ListNode* reverse(ListNode *head) {
        ListNode *node = head, *prior = NULL;
        while (node != NULL) {
            auto next = node->next;
            node->next = prior;
            prior = node;
            node = next;
        }
        return prior;
    }
};
```

```
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode first = head, sec = head;
        while (sec != null && sec.next != null) {
            first = first.next;
            sec = sec.next.next;
        }

        if (sec != null) {
            first = first.next; // odd nodes: let right half smaller
        }

        ListNode pre = null;
        while (first != null) {
            ListNode next = first.next;
            first.next = pre;
            pre = first;
            first = next;
        }

        sec = pre;
        first = head;
        while (sec != null) {
            if (first.val != sec.val) {
                return false;
            }
            first = first.next;
            sec = sec.next;
        }

        return true;
    }
}
```
