用一个数组或者字符串将链表中的值依次存入,然后利用数组遍历方法比较双端元素
class Solution {
public:
bool isPalindrome(ListNode* head) {
string s = "";
ListNode* p = head;
while(p != nullptr){
s.append(to_string(p->val));
p = p->next;
}
int n = s.size();
for(int i = 0; i < n / 2; i++){
if(s[i] != s[n - i - 1]) return false;
}
return true;
}
};
