#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
using namespace std;
int yunsuan(int a, int b, char op){
int res;
if (op == '-')
res = a - b;
if (op == '+')
res = a +b;
if (op == '*')
res = a * b;
if (op == '/')
res = a / b;
return res;
}
int judge (char tmp){
if (tmp == ' ')
return -1;
if (tmp >= '0' && tmp <= '9') {
return 0;
}
else if (tmp == '=')
return 1;
else if (tmp == '-' || tmp == '+')
return 2;
else if (tmp == '*' || tmp == '/')
return 3;
else if (tmp == '(')
return -2;
else if (tmp == ')')
return 4;
}
int main(){
char shizi[100];
stack <int> a;
stack <char> b;
while (~scanf("%s", shizi)){
int len = strlen(shizi);
for (int i = 0; i < len; i++){
if (judge(shizi[i]) == 0)
a.push(shizi[i] - '0');
if (judge(shizi[i]) == 1) {
while (b.empty() != 1) {
int t1 = a.top();
a.pop();
int t2 = a.top();
a.pop();
a.push(yunsuan(t1, t2, b.top()));
b.pop();
}
}
if (judge(shizi[i]) == 2) {
while (b.empty() != 1 && judge(b.top()) >= 2){
int t1 = a.top();
a.pop();
int t2 = a.top();
a.pop();
a.push(yunsuan(t1, t2, b.top()));
b.pop();
}
b.push(shizi[i]);
}
if (judge(shizi[i]) == 3) {
while (b.empty() != 1 && judge(b.top()) >= 3){
int t1 = a.top();
a.pop();
int t2 = a.top();
a.pop();
a.push(yunsuan(t1, t2, b.top()));
b.pop();
}
b.push(shizi[i]);
}
if (judge(shizi[i])== -2)
b.push(shizi[i]);
if (judge(shizi[i]) == 4){
while (b.empty() != 1 && b.top() != '(') {
int t1 = a.top();
a.pop();
int t2 = a.top();
a.pop();
a.push(yunsuan(t1, t2, b.top()));
b.pop();
}
b.pop();
}
}
printf("%d\n", a.top());
a.pop();
}
return 0;
}
栈实现表达式求值
最新推荐文章于 2022-07-02 12:03:53 发布