Mar 9, 2022

Check if list is a palindrome

 #include <iostream>

using namespace std;


class node{

    public:

    char e;

    node* next;

} ;


void printList(node* t)

{

    while(t)

    {

        cout << t->e << "->";

        t=t->next;

    }

    cout << endl;

}

node* buildList(char a[], int n)

{

    node* root = NULL;

    node* prev = NULL;

    for(int i=0; i<n; i++)

    {

        node* iter = new node();

        if(i==0)

        {

         root = iter;

        }

        

        iter->e = a[i];

        iter->next = NULL;

        if(prev)

            prev->next = iter;

        prev = iter;

    }

    


    printList(root);

    return root;

}


bool checkPalindromeRec(node** fwIter, node* revIter)

{

    if(!revIter)

        return true;

    

    bool res = checkPalindromeRec(fwIter, revIter->next);

    if(res && (*fwIter)->e == revIter->e)

    {

        *fwIter = (*fwIter)->next;

        return true;

    }

    

    return false;

}


void checkPalindrome(node* t)

{

    if(checkPalindromeRec(&t, t))

        cout << "it is a palindrome";

    else

        cout << "it is not a palindrome";

}

int main() {

// your code goes here

char a[] = {'a', 'r', 't', 'r', 'a'};

node* root = buildList(a, sizeof(a)/sizeof(a[0]));

checkPalindrome(root);

return 0;

}