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?
/**
* 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 == NULL || head->next == NULL)
return true;
ListNode* fast = head, *slow = head;
while (fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* last = slow->next;
while (last->next) {
ListNode* tmp = last->next;
last->next = tmp->next;
tmp->next = slow->next;
slow->next = tmp;
}
ListNode* pre = head;
while (slow->next) {
slow = slow->next;
if (pre->val != slow->val)
return false;
pre = pre->next;
}
return true;
}
};