力扣-234.回文链表

Idea

用一个数组或者字符串将链表中的值依次存入,然后利用数组遍历方法比较双端元素

AC Code

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;
    }
};

力扣-234.回文链表_第1张图片

你可能感兴趣的:(LeetCode,leetcode,链表,算法)