Implement a function to check if a linked list is a palindrome.
/**
* 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) {
if (!head || !head->next) return true;
ListNode * prev = nullptr, * right = head;
while (right && right->next) {
right = right->next->next;
ListNode * next = head->next;
head->next = prev;
prev = head;
head = next;
}
ListNode * l = prev, * r = head;
if (right) r = r->next
prev = head;
bool is_paline = true;
while (l) {
if (l->val != r->val)
is_paline = false;
ListNode * lnext = l->next;
l->next = prev;
prev = l;
l = lnext; r = r->next;
}
return is_paline;
}
};