share my c++ recursive solution with O(n) time & O(1) space


  • 1
    M
    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            if (head == NULL) return true;
            return rec(head, head->next);
        }
        bool rec(ListNode*& head, ListNode* cur) {
            if (cur == NULL) return true;
            else {
                bool res = rec(head, cur->next) && cur->val == head->val;
                head = head->next;
                return res;
            }
        }
    };
    

  • 0
    P

    Recursion uses function stack.The space is O(1).


Log in to reply
 

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