从中间点开始进行翻转。
class Solution {
public:
ListNode* reverse(ListNode *head)
{
if(!head || !head->next){
return head;
}
ListNode *p = reverse(head->next);
head->next->next = head;
head->next;
return p;
}
bool isPalindrome(ListNode* head) {
if(!head){
return false;
}
ListNode *fast = head;
ListNode *slow = head;
ListNode *pre = slow;
while(fast && fast->next){
fast = fast->next->next;
pre = slow;
slow = slow->next;
}
pre->next = nullptr; // !!!此举是为了把两个相反链表断开
ListNode *tail = reverse(slow);
while(tail && head){
if(tail->val != head->val){
return false;
}
tail = tail->next;
head = head->next;
}
return true;
}
};