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?
/**
* 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) return 1;
ListNode* slow = head;
ListNode *fast = slow;
while(fast && fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode* head2 = slow->next;
slow->next = NULL;
ListNode* pre = NULL;
ListNode* cur = head2;
ListNode* nxt = NULL;
while(head2){
nxt = head2->next;
head2->next = pre;
pre = head2;
head2 = nxt;
}
head2 = pre;
while(head && head2){
if(head->val != head2->val) return 0;
head = head->next;
head2 = head2->next;
}
return 1;
}
};