for Robot Artificial Inteligence

25. Palindrome Linked List

|

/**
 * 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) {
        ListNode* p = head;
        vector<int> stack;
        int size_ = 0;
        while(p)
        {
            stack.push_back(p->val);
            p=p->next;
            size_++;
        }
        int i = 0;
        p=head;
        while(i<size_)
        {
            if(p->val == stack.back())
            {
                stack.pop_back();
                p = p->next;
                i++;
            }
            else
            {
                return false;
            }
        }

        return true;

    }
};

Comments