反转前半部分链表,然后依次比较
/**
* 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 || !head->next) return true;
int n=0;
ListNode *p=head,*pre,*t;
while(p) ++n,p=p->next;
int m=(n>>1);
pre=head,p=pre->next;
while(--m) t=p->next,p->next=pre,pre=p,p=t;
head->next=NULL;//不加会TLE,疑惑点
if(n&1) p=p->next;
while(p && pre){
if(p->val==pre->val) p=p->next,pre=pre->next;
else return false;
}
return true;
}
};