只支持正确格式表达式,判断非法表达式逻辑没写太多
纯个人理解,指套入了部分表达式测试,如有错误欢迎指出
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
typedef struct Operand
{
int and[MAX_SIZE];
int top;
}Operand;
typedef struct Operator
{
int top;
char ator[MAX_SIZE];
}Operator;
//初始化两个栈
void Init_Oper(Operand *p1, Operator *p2)
{
int i = 0;
for (i = 0; i < MAX_SIZE; i++)
{
p1->and[i] = 0;
p2->ator[i] = 0;
}
p1->top = 0;
p2->top = 0;
}
//计算
bool Ifator(char c)
{
switch (c)
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
return true;
default:
return false;
}
}
int Calculate(char ator,int x,int y)
{
switch (ator)
{
case '+':
return x + y;
break;
case '-':
return x - y;
break;
case '*':
return x*y;
break;
case '/':
return x / y;
break;
default:
break;
}
}
void Out(Operand *p1, Operator *p2)
{
int ret = 0;
ret = Calculate(p2->ator[p2->top - 1],
p1->and[p1->top - 2],
p1->and[p1->top - 1]);
p1->and[p1->top - 2] = ret;
p1->and[p1->top - 1] = 0;
p1->top--;
p2->ator[p2->top - 1] = 0;
p2->top--;
}
bool GetAnswer(Operand *p1, Operator *p2, char *expp)
{
bool bracket = false;
while (*expp || (p2->top&&p1->top!=1))
{
int n = 0;
if (isdigit(*expp))//压入操作数
{
while (*expp&&isdigit(*expp))
{
n = n * 10 + *expp-'0';//char型数字需要循环记录完整操作数
expp++;
}
p1->and[p1->top] = n;
p1->top++;
}
else if (Ifator(*expp))//压入操作符 || *expp == '(' || *expp == ')'
{
if (bracket)
{
p2->ator[p2->top] = *expp;
p2->top++;
expp++;
bracket = false;
}
if (0 == p2->top&&*expp!=')')
{
p2->ator[p2->top] = *expp;
p2->top++;
expp++;
}
else
{
if (*expp == '('||p2->ator[p2->top-1]=='(')
{
p2->ator[p2->top] = *expp;
p2->top++;
expp++;
if(*expp == '(')
bracket=true;
}
if (*expp == ')')
{
while (p2->ator[p2->top - 1] != '(')
{
if (!(p2->top))
{
Init_Oper(p1, p2);//非法表达式返回false并清空两个栈
return false;
}
Out(p1, p2);
}
p2->ator[p2->top-1] = 0;
p2->top--;
expp++;
}
if (*expp == '+' || *expp == '-')//下一个运算符为+ - 出栈
{
Out(p1, p2);
}
else if (*expp == '*' || *expp == '/')
{
//+ - 压栈
if (p2->ator[p2->top - 1] == '+' || p2->ator[p2->top - 1] == '-')
{
p2->ator[p2->top] = *expp;
p2->top++;
expp++;
}
// * / 出栈
else if (p2->ator[p2->top - 1] == '*' || p2->ator[p2->top - 1] == '/')
{
Out(p1, p2);
}
}
}
//expp++;
}
else if (!(*expp)&&p2->top)
{
Out(p1, p2);
}
else
return false;
}
if (1==(p1->top - 1) && !(p2->top - 1))
return true;
else
return false;
}
int main()
{
Operand oand;
Operator oator;
char exp[] = "(1+2*1)*3+2*2*2";//17
Init_Oper(&oand, &oator);
GetAnswer(&oand, &oator, exp);
printf("%s\n%d\n", exp, oand.and[oand.top-1]);
system("pause");
return 0;
}