LintCode原题
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?
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head) return true;
ListNode *fast=head,*slow=head,*p,*q=head;
while(fast&&fast->next){
fast=fast->next->next;
slow=slow->next;
}
if(fast) p=reverseList(slow->next);
else p=reverseList(slow);
while(q&&p){
if(q->val!=p->val) return false;
q=q->next;
p=p->next;
}
return true;
}
ListNode* reverseList(ListNode* head){
if(!head) return NULL;
ListNode *pre=new ListNode(-1);
pre->next=head;
while(head->next){
ListNode *p=head->next;
head->next=p->next;
p->next=pre->next;//注意这里不要写成p->next=head;
pre->next=p;
}
return pre->next;
}
};