Clean solution based on list reversal


  • 0
    A
    // reverse list
    ListNode* reverseList(ListNode* prev, ListNode* h) {
      if (!h) return prev;
      ListNode * nxt = h->next;
      h->next = prev;
      return reverseList(h, nxt);
    }
    
    bool isPalindrome(ListNode* h) {
      if (!h) return true;
      ListNode *s = h, *f = h;
      while (f->next && f->next->next) // find mid point
        s = s->next, f = f->next->next;
      s = reverseList(NULL, s->next);
    
      while (h && s) { // compare head and tail
        if (h->val != s->val) return false;
        h = h->next, s = s->next;
      }
      return true;
    }
    

Log in to reply
 

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