Solved programming problem

Find A number is Palindrome or not with Single Linked List in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

node *head=NULL,*n_head=NULL;

int count=0;

void insert_node(int n) ///save the number in a linked list

{

    node *temp;

    while(n>0)

    {

        temp=new node();

        temp->data=n%10;

        temp->next=NULL;

        if(head==NULL)

        {

            count++;

            head=temp;

        }

        else

        {

            count++;

            temp->next=head;

            head=temp;

        }

        n=n/10;

    }

}

void checke_Pali()

{

    node *temp=head,*t;

    int i;

    while(count!=0)

    {

        temp=head;

        i=0;

        while(temp!= NULL) ///save the linked list to another by reverse order

        {

            i++;

            if(i==count)

            {

                t = new node();

                t->data=temp->data;

                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--;

    }

    cout<<"
Linked List: ";

    temp=head;

    while(temp!=NULL) ///print

    {

        cout<<temp->data<<" ";

        temp=temp->next;

    }

    cout<<endl;

    temp=head;

    t=n_head;

    int flag=1;

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

    {

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

        {

            temp= temp->next;

            t= t->next;

            flag=1;

        }

        else

        {

            cout<<"
Its Not A Palindrome Number
";

            return;

        }

    }

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

    return;

}

int main()

{

    int flag=1,n;

    cout<<"Enter The Value: ";

    cin>>n;

    insert_node(n);

    checke_Pali();

    return 0;

}

Output

Enter The Value: 121

Linked List: 1 2 1

It is A Palindrome Number

 

Join the discussion

Add your comment