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 == nullptr || head->next == nullptr)
return true;
ListNode* mid = getmid(head);
ListNode* ptr = reverse(mid);
while (head != mid)
{
if (head->val != ptr->val)
return false;
else
{
head = head->next;
ptr = ptr->next;
}
}
return true;
}
ListNode* getmid(ListNode* head)
{
ListNode* p = head;
ListNode* q = head;
while (p != nullptr && p->next != nullptr)
{
p = p->next->next;
q = q->next;
}
return q;
}
ListNode* reverse(ListNode* head)
{
ListNode* pre = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* post = curr->next;
curr->next = pre;
pre = curr;
curr = post;
}
return pre;
}
};