What's wrong of my c++ code?


  • -2
    N

    I try to reverse the linklist and compare each node.

    class Solution {
        public:
        bool isPalindrome(ListNode* head) {
            if(!head) return true;
        
            ListNode* future = head;
            ListNode* now = NULL;
            ListNode* past = NULL;
            while(future) {
                now = future;
                future = future->next;
                now->next = past;
                past = now;
            }
        
            ListNode* temp1 = head;
            ListNode* temp2 = now;
            while(temp1 && temp2) {
                if(temp1->val!=temp2->val) {
                    return false;
                }
                temp1 = temp1->next;
                temp2 = temp2->next;
            }
            return true;
        }
    };

  • 0
    L

    After reverse, the head is the last element, and head->next is NULL;


  • 0
    N

    Well, I don't change head anymore.


  • 0
    L
        ListNode* future = head;
        ListNode* now = NULL;
        ListNode* past = NULL;
        while(future) {
            now = future;
            future = future->next;
            now->next = past;
            past = now;
        }
    

    at first step of this while cycle, now = head ,past = NULL, and you make now->next = past.


Log in to reply
 

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