pranay_teja
11/20/2018 - 7:24 AM

PalindromeLL-MethodA

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head){
         // Iterative using 3 pointers
        
       if(head==NULL){
           return head;
       }

        ListNode* pre=NULL;
        ListNode* cur=head;
        ListNode* nex=head->next;
        while(nex!=NULL){
            ListNode* temp=nex->next;
            nex->next=cur;
            cur->next=pre;
            pre=cur;
            cur=nex;
            nex=temp;
        }

        // for the last node
        cur->next=pre;
        head=cur;
        return head;

    }
    
    bool isPalindrome(ListNode* head) {

        if(head==NULL || head->next==NULL){
            return true;
        }
        
        int len=0;
        ListNode* cur=head;
        while(cur!=NULL){
            len++;
            cur=cur->next;
        }
        // cout<<"len "<<len<<endl;
        
        int counter;
        if(len&1){ // odd
            // single mid point
            counter=(len/2)+1; // syymetric about mid 7len -> 4mid
        }else{
            counter=(len/2); // symm along with mid 4len -> 2mid
        }
        // cout<<"counter "<<counter<<endl;
        
        int i=1;
        cur=head;
        while(i<counter){
            cur=cur->next;
            i++;
        }
        ListNode* mid=cur;
        
        mid->next=reverse(mid->next); // reverse the list to right of mid
        
        ListNode* leftRunner =head;
        ListNode *rightRunner=mid->next; // runs starting from right of mid
        
        while(true){
            if(leftRunner->val!=rightRunner->val){
                return false;
            }
            if(len&1){
                if(leftRunner->next==mid){
                    return true;
                }
            }else{
                if(leftRunner==mid){
                    return true;
                }
            }
            leftRunner=leftRunner->next;
            rightRunner=rightRunner->next;
        }
        return false;
    }
};