程序如下:
#include
#include
#define stack_init_size 100
#define stackcreament 10
#define ok 1
#define overflow -1
#define error 0
typedef int status;
typedef int elemtype;
typedef struct abc{
elemtype *base;
elemtype *top;
int stacksize;
}sqstack;
status initstack(sqstack &S)
{
S.base=(elemtype *)malloc(stack_init_size *sizeof(elemtype));
if(!S.base)
exit(overflow);
S.top=S.base;
S.stacksize=stack_init_size ;
return ok;
}
status push (sqstack &S,elemtype e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(elemtype *)realloc(S.base,(S.stacksize+stackcreament)*sizeof(elemtype));
if(!S.base)
exit(overflow);
S.top=S.base+S.stacksize;
S.stacksize+=stackcreament;
}
*S.top = e;
S.top=S.top+1;
return ok;
}
status pop(sqstack &S,elemtype &e)
{
if(S.top==S.base)
return error;
S.top=S.top-1;
e=*S.top;
return ok;
}
void match(sqstack S)
{
elemtype ch,x;
ch=getchar();
while(ch!=EOF)
{
switch(ch)
{
case '[':
case '(':
push(S,ch);
break;
case ')':
if(*(S.top-1)=='(' && S.top!=S.base)
pop(S,x);
break;
case ']':
if(*(S.top-1)=='[' &&S.top!=S.base)
pop(S,x);
break;
}
ch=getchar();
}
if(S.base==S.top)
printf("匹配\n");
if(S.base!=S.top)
printf("不匹配\n");
}
int main()
{
sqstack S;
initstack(S);
char ch;
while(ch=getchar()!='#')
match(S);
return 0;
}