#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct Sq{
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));
if(!s->base )
exit(0);
s->stacksize+=STACKINCREMENT;
*(s->top)=e;
s->top ++;
}
void GetTop(SqStack *s,char *e)
{
if(s->top==s->base )
exit(0);
*e=*(s->top-1);
}
void Pop(SqStack *s)
{
if(s->top==s->base )
exit(0);
s->top --;
}
int main()
{
SqStack *s;
s=(SqStack *)malloc(sizeof(SqStack));
InitStack(s);
int flag=1;
int i=0;
char str[128];
printf("请输入算术表达式:");
scanf("%s",str);
char *e=(char *)malloc(sizeof(char));
while(str[i]!='\0'&&flag)
{
switch(str[i])
{
case '[':
Push(s,str[i]);
break;
case '{':
Push(s,str[i]);
break;
case '(':
Push(s,str[i]);
break;
case ']':
if(s->top!=s->base)
{
GetTop(s,e);
if(*e=='[')
{
Pop(s);
flag=1;
break;
}
else
flag=0;
break;
}
else
flag=0;
break;
case ')':
if(s->top!=s->base )
{
GetTop(s,e);
if(*e=='(')
{
Pop(s);
flag=1;
break;
}
else
flag=0;
break;
}
else
flag=0;
break;
case '}':
if(s->top!=s->base )
{
GetTop(s,e);
if(*e=='{')
{
Pop(s);
flag=1;
break;
}
else
flag=0;
break;
}
else
flag=0;
break;
default:
break;
}
i++;
}
if(s->base==s->top)
flag=0;
if(flag==1)
printf("括弧正确!\n");
else
printf("括弧不正确!\n");
return 0;
}
判断表达式中括弧是否正确 C语言
最新推荐文章于 2022-09-01 15:00:09 发布