#include<stdlib.h>
#include<stdio.h>
#define STACK_LIST_SIZE 100
#define STACKINCREMENT 10
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
typedef int status;
typedef struct{
char *base;
char *top;
int stacksize;
}SqStack;
status InitStack(SqStack &S)
{//构造一个空的顺序栈
S.base = (char*)malloc(STACK_LIST_SIZE*sizeof(char));
if (!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_LIST_SIZE;
return OK;
}
status StackEmpty(SqStack S)
{
//判断栈是否为空 如果是返回TRUE 否则返回FALSE
if (!S.base) exit(OVERFLOW);
if (S.base == S.top) return TRUE;
else return FALSE;
}
status Push(SqStack &S, char c)
{
//将c压入栈中作为栈头元素
if (!S.base) exit(OVERFLOW);
if (S.stacksize >= STACK_LIST_SIZE) {
S.base = (char*)realloc(S.base,(STACKINCREMENT+STACKINCREMENT)*sizeof(char));
if (!S.base) exit(OVERFLOW);
S.top = S.base + S.stacksize;
}
*(S.top) = c;
S.top++;
S.stacksize++;
return OK;
}
status Pop(SqStack &S, char &c)
{
//将栈头元素弹出栈 并用c返回其值
if (!S.base) exit(OVERFLOW);
if (S.base == S.top) return ERROR;
c = *(S.top - 1);
S.top--;
return OK;
}
status match(char *pexp)
{
//检测括号是否匹配 如果匹配返回1 不匹配或者栈内还有括号则返回0 表示匹配不成功
SqStack S;
InitStack(S);
int b = 1;//用来判断圆括号是否匹配
int i = 0;//遍历数组
char c;//接收弹出的字符
while (b == 1 && pexp[i] != '\0')
{
if (pexp[i] == '(') Push(S, pexp[i]);
else if (pexp[i] == ')')
{
if (StackEmpty(S)) return ERROR;
else
{
Pop(S, c);
if (c != '(') b = 0;
}
}
i++;
}
return (b&&StackEmpty(S));//不匹配则会返回b==0 未检测到b==0若栈内还有括号则也未匹配
}
int main()
{
char exp[MAXSIZE];
printf_s("Please input the expression(<=100):");
gets_s(exp);
puts(exp);
if (match(exp)) printf("匹配正确\n");
else printf("匹配错误\n");
system("pause");
return 0;
}
判定一个算术表达式中的圆括号是否正确配对
最新推荐文章于 2024-05-31 13:15:53 发布