Problem
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?
Example
Input: 1->2
Output: false
Input: 1->2->2->1
Output: true
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL)
return true;
ListNode *fast=head;
ListNode *slow=head;
ListNode *reverse=NULL;
while(fast->next!=NULL && fast->next->next!=NULL){
fast = fast->next->next;
ListNode *temp = slow;
slow = slow->next;
temp->next = reverse;
reverse = temp;
}
if(fast->next==NULL){
slow = slow->next;
}else{
ListNode *temp = slow;
slow = slow->next;
temp->next = reverse;
reverse = temp;
}
while(slow){
if(slow->val!=reverse->val)
return false;
slow=slow->next;
reverse=reverse->next;
}
return true;
}
};