递归法
class Solution {
ListNode *cur;
public:
bool isPalindrome(ListNode* head) {
cur=head;
return ispalind(head);
}
bool ispalind(ListNode *head){
if(head==nullptr)
return true;
if(!ispalind(head->next))
return false;
if(cur->val!=head->val)
return false;
cur=cur->next;
return true;
}
};
迭代法
快慢指针找中点,将右边反转,判断结束后恢复
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *fast=head,*slow=head;
while(fast->next&&fast->next->next){
fast=fast->next->next;
slow=slow->next;
}
ListNode* temp= reverse(slow->next);
fast=temp;
while(head&&fast){
if(fast->val!=head->val||head==nullptr||fast==nullptr)
return false;
fast=fast->next;
head=head->next;
}
slow->next=reverse(temp);
return true;
}
ListNode *reverse(ListNode *head){
ListNode *pre=nullptr,*next;
while(head){
next=head->next;
head->next=pre;
pre=head;
head=next;
}
return pre;
}
};