表达式求值

发布时间:2022-07-04 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了表达式求值脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

我再也不手写栈了。。。

后缀表达式求值:

建立一个数据栈

如果遇到一个数,把它入栈

如果遇到运算符,弹出栈顶两个数,运算后把结果入栈

中缀转后缀:

建立一个运算符栈

如果遇到一个数,直接输出

如果遇到左括号,入栈

如果遇到左括号,不断弹栈直到栈顶为左括号

如果遇到运算符,不断弹栈直到栈顶的优先级高于新符号,然后把新符号进栈 '*/' > '+-' > '('

弹栈直到清空

 1 #include <iostream>
 2 using namespace std;
 3 
 4 const int maxn = 1e6 + 10;
 5 int st[maxn], rk[maxn], top, cnt, num;
 6 char s[maxn], ans[maxn];
 7 
 8 int main() {
 9   rk[int('^')] = 4;
10   rk[int('*')] = rk[int('/')] = 3;
11   rk[int('+')] = rk[int('-')] = 1;
12   scanf("%s", s);
13   for (int i = 0; s[i] != ''; i++) {
14     if (isdigit(s[i])) ans[++cnt] = s[i];
15     else {
16       if (isdigit(s[i - 1])) ans[++cnt] = '#';
17       if (s[i] == '(') st[++top] = s[i];
18       else if (s[i] == ')') {
19         while (st[top] != '(') ans[++cnt] = st[top--]; 
20         top--;
21       } else {
22         while (rk[st[top]] >= rk[s[i]] && top) ans[++cnt] = st[top--];
23         st[++top] = s[i];
24       }
25     }
26     if (s[i + 1] == '' && isdigit(s[i])) ans[++cnt] = '#'; 
27   }
28 
29   while (top) ans[++cnt] = st[top--];
30 
31   for (int i = 1; i <= cnt; i++) {
32     if (isdigit(ans[i])) {
33       num = num * 10 + ans[i] - '0';
34       continue;
35     }
36     if (ans[i] == '#') {
37       st[++top] = num, num = 0;
38     } else {
39       top--;
40       if (ans[i] == '+') st[top] = st[top] + st[top + 1];
41       else if (ans[i] == '-') st[top] = st[top] - st[top + 1];
42       else if (ans[i] == '*') st[top] = st[top] * st[top + 1];
43       else if (ans[i] == '/') st[top] = st[top] / st[top + 1];
44       else top++;
45     }
46   }
47   cout << st[top];
48   return 0;
49 }

 

logo

脚本宝典总结

以上是脚本宝典为你收集整理的表达式求值全部内容,希望文章能够帮你解决表达式求值所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: