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 == NULL)
{
return true;
}
ListNode *p = head;
ListNode *q = head;
while (p->next && p->next->next)
{
p = p->next->next;
q = q->next;
}
ListNode *midNode = q;
ListNode *secondHead = revert(midNode);
p = head;
q = secondHead;
while (p != NULL)
{
if (p->val != q->val)
{
return false;
}
p = p->next;
q = q->next;
}
revert(midNode);
return true;
}
private:
ListNode* revert(ListNode *head)
{
ListNode *p = head->next;
ListNode *q = head;
while (p != NULL)
{
ListNode *r = p->next;
p->next = q;
q = p;
p = r;
}
head->next = NULL;
return q;
}
};