Solved programming problem

Determine A Linked List is Palindrome or not in C++

Source code

#include <iostream>

 

using namespace std;

 

struct list

{

    int data;

    struct list *next;

};

int count=0;

 

typedef struct list node;

node *head=NULL,*h=NULL;

 

void insert_node() ///insert Function

{

    node *temp=new node();

    node *last;

    count++;

 

    cout<<"Data: ";

    cin>>temp->data;

    temp->next=NULL;

 

    if(head==NULL)

    {

        head=temp;

    }

    else

    {

        last = head;

        while(last->next != NULL)

        {

            last=last->next;

        }

        last->next=temp;

    }

 

}

 

void palindrome()

{

    node *temp;

 

    while(count!=0)

    {

        temp=head;

        int i=0;

        while(temp != NULL)

        {

            i++;

            if(i==count) ///for every last element save a reverse linked list

            {

                node *t=new node();

                t->data=temp->data;

                t->next=NULL;

                if(h==NULL)

                {

                    h=t;

                }

                else

                {

                    node *l=h;

                    while(l->next!=NULL)

                    {

                        l=l->next;

                    }

                    l->next=t;

                }

            }

            temp=temp->next;

        }

        count--;

    }

 

    int flag=1;

    temp=head;

    node *h1=h;

 

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

    {

        if(temp->data != h1->data)

        {

            flag=0;

            break;

        }

        temp= temp->next;

        h1 = h1->next;

    }

 

    if(flag==1)

    {

        cout<<"
It is a Palindrome Linked List"<<endl;

    }

    else

    {

        cout<<"
It is Not a Palindrome Linked List"<<endl;

    }

}

 

void  print()

{

    node *temp=head;

 

    cout<<"
Linked List: ";

 

    while(temp!=NULL) ///print

    {

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

        temp=temp->next;

    }

    cout<<endl;

 

}

int main()

{

    int flag=1;

 

    while(flag==1)

    {

        insert_node();

        cout<<"Press 1 to insert Data Else 0 to Exit: ";

        cin>>flag;

 

    }

 

    print();

 

    palindrome();

 

    return 0;

}

Output

Data: 1
Press 1 to insert Data Else 0 to Exit: 1
Data: 2
Press 1 to insert Data Else 0 to Exit: 1
Data: 1
Press 1 to insert Data Else 0 to Exit: 0

Linked List: 1 2 1

It is a Palindrome Linked List

Join the discussion

Add your comment