|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我写完之后,没有提示错误,但是遇到实际输入就会报错,求助,谢谢,不胜感激
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
typedef int Status;
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
void InitStack(sqStack *s)
{
s->base = (ElemType)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if( !s->base )
{
exit(0);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void Push(sqStack *s, ElemType e)
{
if( s->top - s->base >= s->stackSize )
{
s->base = (ElemType)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if( !s->base )
{
exit(0);
}
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack *s)
{
if( s->top == s->base )
{
return;
}
s->top--;
}
int SrackEmpty(sqStack *s) // 判断空栈
{
return(s->top==0);
}
void Gettop(sqStack *s,ElemType *e)
{
*e = *--(s->top);
s->top++;
}
Status CheckBrackts(char *expr)
{
int i;
char c;
sqStack s;
InitStack(&s);
for( i=0; expr[i]!='\0'; i++)
{
if( expr[i]=='(' || expr[i]=='[' || expr[i]=='{' )
Push(&s, expr[i]); // 遇见左括号,就压入栈中
else if( expr[i]==')' || expr[i]==']' || expr[i]=='}' ) // 遇见右括号,匹配
{
if( SrackEmpty(&s) )
return ERROR;
else
{
Gettop(&s, &c); // 读取栈顶元素,匹配括号
switch( expr[i] )
{
case')':if( c!='(' )
return ERROR;
break;
case']':if( c!='[' )
return ERROR;
break;
case'}':if( c!='{' )
return ERROR;
break;
}
Pop(&s); // 栈顶指针下移
}
}
}
if( SrackEmpty(&s) )
return OK;
else return ERROR;
}
int main()
{
char expr[100];
gets(expr);
if( CheckBrackts(&expr) )
printf("yes");
else
printf("no");
return 0;
}
|
|