请判断一个链表是否为回文链表。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head)
return true;
//利用快慢指针找出链表的中点
ListNode* fast=head;
ListNode* slow=head;
while(fast->next&&fast->next->next){
fast=fast->next->next;
slow=slow->next;
}
ListNode* cur=slow;
if(fast->next) //链表长度为偶数时,应该从slow指针的下一个结点开始链表反转
{
cur=cur->next;
//slow->next=NULL; //若后面使用cur判断是否为空,必须加上这句;也可以不加这句,后面比较的时候判断pre是否为空
}
//从cur开始反转链表
ListNode* pre=NULL;
while(cur){
ListNode* next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
//前段链表从head开始,后段链表从反转后的表头pre开始
cur=head;
while(pre){ //这里若用cur判断,之前就必须加上slow->next=NULL;
if(cur->val!=pre->val)
return false;
cur=cur->next;
pre=pre->next;
}
return true;
}
};