Wednesday, December 29, 2010

general palindrome check using stack

/****************************
* Umang B Bhatt *
* bhatt.umang7@gmail.com *
*****************************/

/**
* program for general palindrome string
*/


#include<stdio.h>
#include<string.h>

#define MAX 100
#define TRUE 1
#define FALSE 0

int
push(char *s, int top, char ele)
{


int
i;
if
(top >= MAX)
{


printf("\nStack Overflow");
}

else

{

s[++top] = ele;
}


return
top;
}


int
pop(char *a, int *top)
{


if
((*top) >= 0)
{
(*
top) = (*top) - 1;

return
a[(*top) + 1];
}

else

{


printf("Stack underflow\n");
return
0;
}
}


void
main()
{


int
i;
char
a, b;
char
c[MAX];

int
valid = TRUE;
int
TOP = -1;

char
s[MAX];
printf("Enter string: ");
gets(c);

//remember that using gets() function is not safe.
for (i = 0; i < strlen(c) / 2; i++)
{


TOP = push(s, TOP, c[i]);
}


for
(; c[i] != '\0'; i++)
{

if
(TOP < 0)
{


valid = FALSE;
break
;
}

else

{


a = pop(s, &TOP);
if
(c[i] != a)
{


valid = FALSE;
}
}
}

if
(valid == TRUE)
{


printf("Valid palindrome string\n");
}

else

{

printf("Invalid palindrome string\n");
}
}


2 comments:

  1. hi, i think there's a little bug there.
    if the number of character is odd, it will return "Invalid palindrome string" regardless it's a palindrome or not.

    to fix it, just add c[i] by one if strlen(c) is odd above this part:
    --for (; c[i] != '\0'; i++)--
    CMIIW

    ReplyDelete
  2. this is a general palindrome string.
    its format is WWR.
    so this one is correct as per my knowledge.

    what you are telling is also correct. But that is for WcWr.
    (i think)



    the WWr string will always have even number of characters.

    ReplyDelete