leetcode 面试题 02.06. 回文链表

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> vec;
        while(head)
        {
            vec.push_back(head->val);
            head = head->next;
        }
        if(vec.size() < 2)
        {
            return true;
        }
        if(vec.size() == 2)
        {
            if(vec[0] == vec[1])
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        for(int i = 0; i < vec.size() / 2; i++)
        {
            if(vec[i] != vec[vec.size() - 1 - i])
            {
                return false;
            }
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43956456/article/details/107688025
今日推荐