【题目描述】
输入一个中缀表达式(由0-9组成的运算数、加+减-乘*除/四种运算符、左右小括号组成。注意“-”也可作为负数的标志,表达式以“@”作为结束符),判断表达式是否合法,如果不合法,请输出“NO”;否则请把表达式转换成后缀形式,再求出后缀表达式的值并输出。
注意:必须用栈操作,不能直接输出表达式的值。
【输入】
一行为一个以@结束的字符串。
【输出】
如果表达式不合法,请输出“NO”,要求大写。
如果表达式合法,请输出计算结果。
【输入样例】
1+2*8-9@
【输出样例】
8
#include<cstdio>
#include<iostream>
using namespace std;
const int N = 1000;
char a[N] = {0};
char c[N] = {0};
int n[N] = {0};
int ntop, ctop;
bool symbol(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
return true;
}
return false;
}
void calc(char ch)
{
if (ch == '+') {
n[--ntop] += n[ntop + 1];
} else if (ch == '-') {
n[--ntop] -= n[ntop + 1];
} else if (ch == '*') {
n[--ntop] *= n[ntop + 1];
} else if (ch == '/') {
n[--ntop] /= n[ntop + 1];
}
}
bool first(char ch1, char ch2)
{
if (ch1 == '-' || ch1 == '+') {//默认不运算
if (ch2 == '-' || ch2 == '+') {
return true;
}
return false;
}
if (ch1 == '*' || ch1 == '/') {//默认要运算
return true;
}
return false;
}
int main()
{
gets(a);
int cm = 0, cn = 0;
for (int i = 0; a[i] != '\0'; i++) {
if (a[i] >= '0' && a[i] <= '9') {
int x = 0;
while (a[i] >= '0' && a[i] <= '9') {
x = x * 10 + a[i] - '0';
i++;
}
n[++ntop] = x;
}
if (a[i] == '(') {
c[++ctop] = '(';
cm++;
}
if (a[i] == ')') {
cn++;
while (c[ctop] != '(') {
calc(c[ctop]);
ctop--;
}
ctop--;
}
if (symbol(a[i])) {
while (first(c[ctop], a[i])) {
calc(c[ctop]);
ctop--;
}
ctop++;
c[ctop] = a[i];
}
if (symbol(a[i]) && symbol(a[i + 1])) {
cout << "NO";
return 0;
}
}
while (ctop != 0) {
calc(c[ctop]);
ctop--;
}
if (cm != cn) {
cout << "NO";
return 0;
}
cout << n[ntop];
return 0;
}