Solved programming problem

Find A String is Palindrome or not with Single Linked list in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    char c;

    struct list *next;

};

typedef struct list node;

node *head=NULL,*n_head=NULL;

int count=0;

void insert_node(char str[]) ///convert string to linked list

{

    int i=0;

    node *temp;

    while(str[i]!='')

    {

        temp=new node();

        temp->c=str[i];

        temp->next=NULL;

        if(head==NULL)

        {

            count++;

            head=temp;

        }

        else

        {

            count++;

            node *last=head;

            while(last->next!=NULL)

            {

                last=last->next;

            }

            last->next=temp;

        }

        i++;

    }

    temp=head;

    cout<<"
Linked List: ";

    while(temp!=NULL) ///print

    {

        cout<<temp->c<<" ";

        temp=temp->next;

    }

    cout<<endl;

}

void  cheake_pali()

{

    node *temp=head;

    int i;

    while(count!=0) ///save the linked list revers to another linked list

    {

        i=0;

        temp=head;

        while(temp!=NULL)

        {

            i++;

            if(i==count)

            {

                node *t = new node();

                t->c=temp->c;

                t->next=NULL;

                if(n_head==NULL)

                {

                    n_head=t;

                }

                else

                {

                    node *last=n_head;

                    while(last->next!=NULL)

                    {

                        last = last->next;

                    }

                    last->next=t;

                }

            }

            temp=temp->next;

        }

        count--;

    }

    node *t=n_head;

    temp=head;

    int flag=1;

    while(t!=NULL && temp!=NULL) ///compare two linked list

    {

        if(t->c==temp->c)

        {

            t=t->next;

            temp= temp->next;

            flag=1;

        }

        else

        {

            cout<<"It is Not A Palindrome Word "<<endl;

            return;

        }

    }

    if(flag==1)cout<<"It is A Palindrome Word "<<endl;

    return;

}

int main()

{

    char str[10];

    cin>>str;

    insert_node(str);

    cheake_pali();

    return 0;

}

Output

maddam

Linked List: m a d d a m
It is A Palindrome Word

Join the discussion

Add your comment