1.题目描述

2.思路
前面两题都是为了这一题做准备的,思路就是双指针先找到中间节点,然后翻转后半段,然后依次对比即可
3.代码
cpp
bool isPalindrome(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return true;
}
struct ListNode* p1 = head;
int len = 0;
while(p1!=NULL){
len++;
p1 = p1->next;
}
int mid = len/2;//找到后半段的首个节点
p1 = head;//继续用p1
while(mid>0){
p1 = p1->next;
mid--;
}//此时p1指向后半段
//开始反转后半段
struct ListNode* pre = NULL;
struct ListNode* cur = p1;
struct ListNode* nextp=NULL;
while(cur!=NULL){
nextp = cur->next;
cur->next = pre;
pre = cur;
cur=nextp;
}
//此时cur就是后半段反转的头节点
//开始判断回文
while(pre!=NULL){
if(head->val != pre->val){
return false;
}
pre = pre->next;
head = head->next;
}
return true;
}