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?
solution: two pointers, one pointer step 1, the other pointer step 2, find the mid node, reverse the start->mid node.
/**
* 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* h1 = head;
ListNode* h2 = head;
ListNode* left = NULL;
ListNode* right = NULL;
ListNode* before = NULL;
while(1)
{
//even
if(h2 == NULL)
{
right = h1;
left = before;
break;
}
//odd
else if(h2->next == NULL){
left = before;
right = h1->next;
break;
}
else{
h2 = h2->next->next;
ListNode* tmp = h1->next;
h1->next = before;
before = h1;
h1 = tmp;
}
}
while(left!= NULL && right!= NULL){
if(left->val == right->val)
{
left = left->next;
right = right->next;
}else{
return false;
}
}
return true;
}
};