Stack Program #2
16. Write a program to determine if an input string is of the form “aibi” where i >= 1 using Stack.i.e. Number of ‘a’ should be equal to number of ‘b’ (Example - ab, aabb, abab etc. are valid and
aab, bba etc. are invalid strings.)
#include<stdio.h>
#define n 50
char s[n];
int top=-1;
void push(char) ;
char pop();
void main()
{
char str[50],countb=0,i,x;
printf("enter a string which containing a and b = ");
scanf("%s", str);
while(str[i]!='\0')
{
if(str[i]=='a')
{
push(str[i]);
}
else if(str[i]=='b')
{
countb++;
}
i++;
}
while(top!=-1)
{
x=pop();
countb=countb-1;
}
if(countb==0)
{
printf("valid string \n \n");
}
else
{
printf("invalid string \n \n");
}
}
void push(char x)
{
if(top>=n-1)
{
printf("stack overflow");
}
else
{
top++;
s[top]=x;
}
}
char pop()
{
if(top==-1)
{
return 'z';
}
else
{
top=top-1;
return s[top+1];
}
}
#define n 50
char s[n];
int top=-1;
void push(char) ;
char pop();
void main()
{
char str[50],countb=0,i,x;
printf("enter a string which containing a and b = ");
scanf("%s", str);
while(str[i]!='\0')
{
if(str[i]=='a')
{
push(str[i]);
}
else if(str[i]=='b')
{
countb++;
}
i++;
}
while(top!=-1)
{
x=pop();
countb=countb-1;
}
if(countb==0)
{
printf("valid string \n \n");
}
else
{
printf("invalid string \n \n");
}
}
void push(char x)
{
if(top>=n-1)
{
printf("stack overflow");
}
else
{
top++;
s[top]=x;
}
}
char pop()
{
if(top==-1)
{
return 'z';
}
else
{
top=top-1;
return s[top+1];
}
}
Output
- enter a string which containing a and b = abab
valid string - enter a string which containing a and b = abbab
invalid string
Comments
Post a Comment