leetcode-234. 回文链表

 

 

/**
 * 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);
    }
};

 

posted @ 2021-07-24 11:13  三一一一317  阅读(35)  评论(0)    收藏  举报