一、题目
二、思路
1、快慢指针找到后半段链表
2、反转后半段链表
3、将前半段和后半段比较
三、代码
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==nullptr){
return true;
}
ListNode *mid=MidNode(head);
ListNode *NewNode=Reverse(mid);
while(head!=nullptr && NewNode!=nullptr){
if(head->val!=NewNode->val){
return false;
}
head=head->next;
NewNode=NewNode->next;
}
return true;
}
//找到后半部分的开始结点
ListNode *MidNode(ListNode* head){
ListNode *fast=head;
ListNode *slow=head;
while(fast->next!=nullptr && fast->next->next!=nullptr){
fast=fast->next->next;
slow=slow->next;
}
return slow->next;
}
//反转后半部分链表
ListNode *Reverse(ListNode* head){
ListNode *pre=nullptr;
ListNode *cur=head;
ListNode *nxt=nullptr;
while(cur){
nxt=cur->next;
cur->next=pre;
pre=cur;
cur=nxt;
}
return pre;
}
};