输入“ [ ] ”为什么不匹配,求高手指点
#include <stdio.h >#include <stdlib.h>
#define OVERFLOW -2
#define OK 1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char SElemType ;
typedef int Status ;
typedef struct {
SElemType *base ;
SElemType *top ;
int stacksize ;
} SqStack ;
Status StackEmpty (SqStack s )
{ if (s.base==s.top) return 1;
else return 0 ;
} //stackempty
Status InitStack (SqStack &s)
{ s.base=(SElemType *)malloc (STACK_INIT_SIZE *sizeof (SElemType )) ;
if (!s.base) exit (OVERFLOW ) ;
s.top = s.base ;
s.stacksize =STACK_INIT_SIZE ;
return OK ;
}//initstack
Status Push (SqStack &s ,SElemType e )
{ if (s.top -s.base >=s.stacksize )//栈满,追加存储空间
{ s.base = (SElemType *) realloc (s.base,(s.stacksize +STACKINCREMENT)
*sizeof (SElemType) ) ;
if (!s.base) exit ( OVERFLOW ) ;//存储分配失败
s.stacksize +=STACKINCREMENT ;
}
*s.top++=e ;
return OK ;
}//push
Status Pop (SqStack &s , SElemType *e)
{ if (s.top==s.base ) return 0 ;
*e =*--s.top ;
return OK ;
}// pop
Status GetTop (SqStack s ,SElemType *e )
{ if (s.top ==s.base ) return 0 ;
*e = *(s.top-1) ;
return 1 ;
}//gettop
main ()
{ int i=0 ;
SqStack s ;
char a[20] , ch ,e ;
InitStack ( s) ;
printf ("请输入括号且长度不能超过20 :\n") ;
while ((ch=getchar())!='\n')
{ a[i]=ch ;
i++ ;
}
for (i=0 ;a[i]!='\n' ;i++)
{ switch (a[i])
{ case '(' :
case '[' :
case '{' :
Push (s ,a[i]) ; break ;
case ')' :
case '}' :
case ']' :
if (StackEmpty (s ))
{printf ("括号不匹配\n") ; return ;}
else { GetTop (s,&e) ;
if ((a[i]-e==1)||(a[i]-e==2))
Pop (s , &e ) ;
else { printf ("括号不匹配\n"); return ; }
}
}
}
if ( StackEmpty (s))
printf ("括号匹配\n") ;
else printf ("括号不匹配\n") ;
}