O(n) time and O(1) space C++ solution with easy-understand comments


  • 2
    T
    bool isPalindrome(ListNode* head) {
        int len = 0;
        ListNode *p = head;
        
        /* get length of the link */
        while(p){
            len++;
            p = p->next;
        }
        
        /* get next node of middle of link */
        p = head;
        int mid = len / 2;
        while(mid--) p = p->next;
        if(len % 2 == 1) p = p->next;
    
        /* reverse the back of the link */
        ListNode *prev = NULL, *next = NULL;
        while(p){
            next = p->next;
            p->next = prev;
            prev = p;
            p = next;
        }
        
        /* jude palindrome */
        p = prev;
        while(p){
            if(head->val != p->val) return false;
            head = head->next;
            p = p->next;
        }
        return true;
    }

Log in to reply
 

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