面试题 02.06. Palindrome Linked List LCCI

Problem

Implement a function to check if a linked list is a palindrome.

Example1

Input: 1->2
Output: false

Example2

Input: 1->2->2->1
Output: true

Solution

/**
 * 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) {
        if(!head || !head->next)
            return true;

        ListNode *cur = head;
        vector<int> vals;
        while(cur)
        {
            vals.push_back(cur->val);
            cur = cur->next;
        }

        int i = 0;
        int j = vals.size() - 1;

        while(i < j)
        {
            if(vals[i] != vals[j])
            {
                return false;
            }
            else
            {
                ++i;
                --j;
            }
        }

        return true;

    }
};
发布了526 篇原创文章 · 获赞 215 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105106237