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?
s思路:
1. 套路题。先快慢指针找到中点,然后把后半部分reverse,然后两边都从头开始遍历,看是否相等。
class Solution {
public:
bool isPalindrome(ListNode* head) {
//
if(!head) return true;
ListNode* fast=head->next,*slow=head;
//step 1: 找中点
while(fast&&fast->next){
fast=fast->next->next;
slow=slow->next;
}
//step 2:reverse the right half
ListNode* pre=NULL,*pnow=slow->next,*pnext=NULL;
slow->next=NULL;
while(pnow){
pnext=pnow->next;
pnow->next=pre;
pre=pnow;
if(!pnext) break;
pnow=pnext;
}
//step 3:逐一比较
ListNode* l=head,*r=pnow;
while(r){
if(r->val!=l->val) return false;
r=r->next;
l=l->next;
}
return true;
}
};