
/**
* 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:
vector<int> res;
bool isPalindrome(ListNode* head) {
if(head==NULL)
return false;
retree(head);
for(int i = 0; i < res.size(); i++){
if(head->val!=res[i]) // 比较数组中元素和链表中元素是否相等
return false;
else
head = head->next;
}
return true;
}
// 递归,将链表逆置存放到数组中。
void retree(ListNode* head){
if(head==NULL)
return;
retree(head->next);
res.push_back(head->val);
}
};