Pages

Custom Search
Showing posts with label palindrome. Show all posts
Showing posts with label palindrome. Show all posts

Monday, October 10, 2011

Program to check if entered string is palindrome or not using stack.


/*A string is said to be palindrome when the reverse of the string is same as that of the original string
   For ex: Entered string: madam... is a palindrome*/

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define SIZE 10

typedef struct
{
        int items[SIZE];
        int top;

}STACK;


void push();
int pop();
void display();
int isoverflow();
int isempty();

int main()
{
        STACK s;
        char str[100];
        int i, flag;

        s.top = -1;

        printf("\nEnter a string: ");
        gets(str);

        for(i=0;str[i]!='\0'; i++)
                  push(&s, str[i]);

        flag = 1;
        for(i=0;str[i]!='\0';i++)
        {
                if(str[i] != pop(&s))
                {
                        flag = 0;
                        break;
                }
        }

if(flag == 1)
                printf("\nEntered string is palindrome\n");
        else
                printf("\nEntered string is not a palindrome\n");

}

void push(STACK *p, int element)
{
           if(isoverflow(p->top))
           {
                    printf("\nStack is overflow");
           }
           else
          {
                  (p->top)++;
                   p->items[p->top] = element;
          }
}

int pop(STACK *p)
{
         if(isempty(p->top))
         {
                  printf("\nStack is underflow");
         }
         else
         {
                  return (p->items[(p->top)--]);
         }
}

void display(STACK s)
{
        int i;
        if(isempty(s.top))
        {
printf("\nStack is empty");
        }
        else
        {
                for(i=s.top; i>=0; i--)
                {
                        printf("\n%d", s.items[i]);
                }
        }
}

//Function to check stack overflow condition
int isoverflow(int top)
{
        if(top == SIZE - 1)
                return (1);
        else
                return (0);
}

//Function to check stack empty condition
int isempty(int top)
{
         if(top == -1)
                return (1);
        else
                return (0);
}

SAMPLE OUTPUT:




Custom Search