leetcode 234. 回文链表

2023.9.5

leetcode 234. 回文链表_第1张图片        本题先将链表的节点值移到数组中,再用双指针去判断该数组是否为回文的即可。 代码如下:

/**
 * 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:
    bool isPalindrome(ListNode* head) {
        vector nums;
        while(head)
        {
            nums.push_back(head->val);
            head = head->next;
        }
        int left = 0;
        int right = nums.size()-1;
        while(left <= right)
        {
            if(nums[left] != nums[right]) return false;
            left++;
            right--;
        }
        return true;
    }
};

你可能感兴趣的:(leetcode专栏,leetcode,链表,算法,数据结构,cpp)