mercredi 7 juillet 2021

I've made this code to figure out if a given linked list is palindrome. it's failing in the case [1,1,2,1]

I'm reversing(reverse) the linked list and comparing it with the original list if both are equal. It's a palindrome otherwise it's not.

   void reverse(ListNode *&N)     //reversing the copy of linked list
      {
         ListNode *one,*two,*three;
         one=N;
         two=N;
         three=NULL;
         while(one)
         {
            one=one->next;
            two->next= three;
            three=two;
            two=one;

          }
             N=three;
        }

    bool isPalindrome(ListNode* head)
    {
        ListNode* rev = head;
        ListNode *temp=head;
        reverse(rev);
        while(temp)                         //checking if reverse and original are equal
        {
            if(rev->val!= temp->val)return false;
            rev=rev->next;
            temp=temp->next;
        }
        return true;
    }
```C++

Aucun commentaire:

Enregistrer un commentaire