- 思路
找到最中间开始相同的部分,对后部分链表进行反转,再将前半部分与后半部分逐一比较是否相同 - 错误
要注意循环终止条件
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *temp, *newhead = NULL;
while(head!=NULL){
temp = head;
head = head->next;
temp->next = newhead;
newhead = temp;
}
return newhead;
}
bool isPalindrome(struct ListNode* head){
if(head==NULL || head->next==NULL){
return true;
}
if(head->next->next==NULL){
if(head->val==head->next->val)
return true;
else
return false;
}
struct ListNode* p = head;
struct ListNode* p1 = head->next;
struct ListNode* p2 = head->next->next;
while(p2!=NULL){
if(p->val==p1->val){
p1 = reverseList(p1);
while(p1!=NULL){
if(head->val != p1->val)
return false;
head = head->next;
p1 = p1->next;
}
return true;
}
if(p->val==p2->val){
p2 = reverseList(p2);
while(p2!=NULL){
if(head->val != p2->val)
return false;
head = head->next;
p2 = p2->next;
}
return true;
}
p = p->next;
p1 = p1->next;
p2 = p2->next;
}
return false;
}