Linked List in C- Check whether Linked List is Palindrome using Recursion

Linked List in C- Check whether Linked List is Palindrome using Recursion

Linked List in C- Check whether Linked List is Palindrome using Recursion

DATA STRUCTURES IN C – LINKED LIST (20 PROGRAMS)

Linked List in C- Check whether Linked List is Palindrome using Recursion :

Source Code :

#include<stdio.h>
struct node
{
    int data;
    	struct node *next;
};

void print(struct node **head)
{
    	struct node *temp=*head;
    	printf("\nList:");
	    while(temp!=NULL)
    	{
        		printf("\n%d",temp->data);
        		temp=temp->next;		
    	}
}

int palindrome(struct node **left,struct node *right)
{
    	if(right==NULL)
    	{
        		return 1;
    	}
    	int result=palindrome(left,right->next);
    	if(result==0)
    	{
        		return 0;
    	}
	    if((*left)->data==right->data)
	    {	
        		*left=(*left)->next;
        		return 1;
    	}
	    return 0;
}

int main()
{
    	struct node *one = (struct node*)malloc(sizeof(struct node));
    	struct node *two = (struct node*)malloc(sizeof(struct node));
    	struct node *three = (struct node*)malloc(sizeof(struct node));
    	struct node *four = (struct node*)malloc(sizeof(struct node));

    	struct node *head=one;

    	one->data=1;
    	one->next=two;

    	two->data=2;	
    	two->next=three;

    	three->data=2;
    	three->next=four;

    	four->data=1;
    	four->next=NULL;

    	print(&head);

    	int result=palindrome(&head,head);	

    	if(result==1)
    	{
        		printf("\nPalindrome");
    	}
    	else
    	{
        		printf("\nNot Palindrome");
    	}

    	return 0;
}

Output :

List:
1
2
2
1

Palindrome

[ YOU MAY ALSO LIKE ]

Leave a Reply