Search code examples
calgorithmlinked-listsingly-linked-listpalindrome

Palindrom check of linkedlist


Here is the code i wrote to check if a singly linked list of integers is a palindrome or not.

#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *next;
};
struct list *insert(int data,struct list *node)
{
 if(node==NULL)
 {
    node=(struct list *)malloc(sizeof(struct list));
    node->data=data;
    node->next=NULL;
}
else
{
    struct list *newnode=(struct list *)malloc(sizeof(struct list));
    newnode->data=data;
    newnode->next=node;
    node=newnode;
}
return node;
 }

int palindrome(struct list *node,int n)
{
int i=0;int j=0;
   int arr1[n],arr2[n];
   struct list *current;
   current=node;
 while(current!=NULL)
 {
    arr1[i]=current->data;
    i++;
    current=current->next;
}
i=0;j=0;
  for(i=n-1;i>=0;i--)
  {
    arr2[j]=arr1[i];
    j++;
}
for(i=0;i<n;i++)
{
    if(arr1[i]!=arr2[i])
    {
        return 0;
    }
}
return 1;
}
 void main()
{
 int n;
 scanf("%d",&n);
 struct list *node=NULL;
 int i=1;int value;
 for(i=1;i<=n;i++)
 {
    scanf("%d",&value);
     insert(value,node);
 }
 int status=palindrome(node,n);
 printf("%d",status);
 }

But the code returns 0 even in case of valid palindrome inputs like "121" and also in non - palindrome inputs like "154". Please help. Thanks


Solution

  • You need to write

    node = insert(value,node);
    

    in main. Otherwise the head node is not changed because the function insert deals with a copy of the node.