C语言检测表达式括号是否匹配

?#include
#include
#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct
{
char *base;
char *top;
int stacksize;
}SqStack;

void InitStack(SqStack &S)
{
S.base = (char*)malloc(STACK_INIT_SIZE*sizeof(char));
if (!S.base)
{
exit(0);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}

void Push(SqStack &S, char e)
{
if (S.top - S.base >= S.stacksize)
{
S.base = (char *)realloc(S.base, (S.stacksize + STACKINCREMENT)*sizeof(char));

S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
if (!S.base)
{
exit(0);
}
*S.top = e;
S.top++;
printf("入栈\n");
}

void Pop(SqStack &S)
{
if (S.top == S.base)
{
return ;
}
S.top--;
printf("出栈\n");
}

void DestoryStack(SqStack &S)
{
free(S.base);
}


int main()
{
SqStack S;
InitStack(S);
char str[200];
printf("输入数据\n");
gets_s(str);//读入一串括号 小括号或大括号
puts(str);
int i;
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] ==')')
{
if (*(S.top - 1)== '(')
{
Pop(S);
}
else
{
printf("不匹配la\n");
return 0;
}
}
else if (str[i] == '}')
{
if (*(S.top - 1) == '{')
{
Pop(S);
}
else
{
printf("不匹配\n");
return 0;
}
}
else
{
Push(S, str[i]);
}
}



if (S.top == S.base)
{
printf("匹配\n");
}
else
{
printf("不匹配\n");
}
return 0;
}



相关主题
相关文档
最新文档