Wednesday, December 29, 2010

wcwr palindrome using stack

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

/**
* program for wcwr palindrome string
*/


#include<stdio.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];
//remember that declraing the stack as global is not a good practice (according to my openion)
printf("Enter string: ");
gets(c);

TOP = push(s, TOP, 'c');
for
(i = 0; c[i] != 'c'; i++) // you can modify this string as you want

{ // some people may modify to go upto n/2 etc
TOP = push(s, TOP, c[i]);
}



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


if
(TOP < 0)
{

valid = FALSE;

break
;
}
else
{

a = pop(s, &TOP);

if
(c[i] != a)
{

valid = FALSE;
}
}

}


if
(TOP == 0)
{

a = pop(s, &TOP);

if
(a != 'c')
{

valid = FALSE;
}
}
else

{

valid = FALSE;
}

if
(valid == TRUE)
{


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

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


No comments:

Post a Comment