To solve it with only O(1) space, you can only find the mid point of the linked list and do some reverse operation, so that you are able to traverse back. To find the mid point, use the fast and slow method, and once the mid point is found, reverse the latter half and compare.
/**
* 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) {
ListNode *slow,*fast;
slow=fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
reverse(slow,fast);
slow=head;
while(fast)
{
if(slow->val!=fast->val)
return false;
slow=slow->next;
fast=fast->next;
}
return true;
}
ListNode* reverse(ListNode* root,ListNode*& end)
{
if(!root||!root->next)
{
end=root;
return root;
}
ListNode* temp=reverse(root->next,end);
temp->next=root;
root->next=NULL;
return root;
}
};