C++ O(n) time and O(n) memory solution.


  • 0
    J
    /**
     * 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 == NULL)
                return true;
            vector<int> l;
            while (head != NULL) {
                l.push_back(head->val);
                head = head->next;
            }
            int start = 0, end = l.size() - 1;
            while (start < end) {
                if (l[start++] != l[end--])
                    return false;
            }
            return true;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.