Sunday, June 23, 2013

Working program for Palindrome finding using Singly Linkedlist


// Working program for Palindrome using Singly LinkedList
#include <stdio.h>
#include <stdlib.h>
typedef struct Linkedlist
{
    int data;
    struct Linkedlist *next;
}List;

void Insertnode(List **head,int data)
{
List *ptr=*head,*temp;
temp=(List*)malloc(sizeof(List));
if(!temp)return;
temp->data=data;
temp->next=NULL;
if(!ptr)
*head=temp;
else
{
 while(ptr->next)
  ptr=ptr->next;
 ptr->next=temp;
 }
}

List *Partition(List **Head)
{
    if(!*Head) return;
    List *temp,*sptr=*Head,*head=*Head;
    while(head)
    {
    head=head->next;
    if(!head){temp->next=NULL; return sptr;}
 
    head=head->next;
    temp=sptr;
    sptr=sptr->next;
 
    }
temp->next=NULL;
return sptr;
}
List *Reverse(List *head)
{
List *temp,*prev=NULL,*ptr=head;
while(ptr->next)
{   temp=ptr;
    ptr=ptr->next;
    temp->next=prev;
    prev=temp;
}
ptr->next=prev;
return ptr;
}

void Matching(List *head,List *tail)
{
    if(!head||!tail)
    return;
    if(head->data==tail->data||head->data+32==tail->data)
    {head=head->next;
     tail=tail->next;
    }
    else
    {printf("\nNot a palindrome");return ;}
 
    while(head->data==tail->data)
   {
       head=head->next;
       if(head==NULL) {printf("\nPalindrome\n");return;}
       tail=tail->next;
   
   }
   printf("\nNot a palindrome\n");
}

void Palindrome(List *head)
{  List *tail=NULL;
    if(!head)return ;
    tail=Partition(&head);
    tail=Reverse(tail);
    Matching(head,tail);
}


main()
{
 List *Head=NULL;
 int i=0,data;

 while(i<7)                  // You may change if no. of character increases as per.
 {
 scanf("%c",&data);
 Insertnode(&Head,data);
 i++;
 }
Palindrome(Head);
}

No comments:

Post a Comment