Wednesday, 8 February 2017

C++ Program To Check if a Linked List is Palindrome or not by using Array

Linked list is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. C++ program is given below to check if a Linked List is palindrome or not.
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
}*root=NULL,*newnode;
int arr1[50],arr2[50];
void print()
{
       struct node *current;
       current=root;
       while(current!=NULL)
       {
               printf("%d->",current->data);
               current=current->next;
       }
}
void insert(int item)
{

       if(root==NULL)
       {
            newnode=(struct node*)malloc(sizeof(struct node));
            newnode->data=item;
            newnode->next=NULL;
            root=newnode;
       }
       else
       {
            newnode->next=(struct node*)malloc(sizeof(struct node));
            newnode=newnode->next;
            newnode->data=item;
            newnode->next=NULL;
       }
}
bool palindrome()
{
       struct node *current;
       current=root;
       int i=0,n=0;
       while(current!=NULL)
       {
            arr1[i]=current->data;
            i++;
            n++;
            current=current->next;
       }
       int j=0;
       for(i=n-1;i>=0;i--)
       {
            arr2[j]=arr1[i];
            j++;
       }
       printf("\n");
       for(i=0;i<=n;i++)
       {
            if(arr1[i]!=arr2[i])
            {
                return false;
            }
       }
       return true;

}
int main()
{
       int ch,item;
       do
       {
            printf("\nEnter the element: ");
            scanf("%d",&item);
            insert(item);
            printf("\nDo you want to continues insert elements[1/0] ?? ");
           scanf("%d",&ch);
       }while(ch==1);
       printf("\nLinkedList is: \n\n");
       print();
       if(palindrome()==true)
       {
            printf("\nYes, The above LinkedList is a palindrome");
       }
       else
       {
            printf("\nNo, The above LinkedList is not a palindrome");
       }
       return 0;
}

OUTPUT 1:  


OUTPUT 2:

 


EmoticonEmoticon