[leetcode]Palindrome Linked List

This problem asks to determine if a singly linked list is a palindrome. My original idea was to reverse the first half of the linked list and then traverse again, which should meet the time complexity $O(n)$ and space complexity $O(1)$ requirements, but it kept getting a time limit exceeded error for some reason.
After checking the discuss section and hints, a simple recursion actually works.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    ListNode * temp;
    bool isPalindrome(ListNode* head) {
        temp = head;
        return check(head);
    }

    bool check(ListNode * node) {
        if (node == NULL) return true;
        bool flag = check(node->next) && (node->val == temp->val);
        temp = temp->next;
        return flag;
    }
};