ALGO-156
Posted 小九
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ALGO-156相关的知识,希望对你有一定的参考价值。
题目链接:http://lx.lanqiao.cn/problem.page?gpid=T419
将中缀表达式通过栈转换为后缀表达式
#include<iostream> #include<sstream> #include<string> #include<stack> #include<vector> using namespace std; bool higher(char a, char b) { if (b == ‘(‘ || b == ‘)‘) return 1; if (a == ‘*‘ || a == ‘/‘) if (b == ‘+‘ || b == ‘-‘) return 1; return 0; } void stack_vec(stack<char>&s, vector<string>&suffix) { string str; str += s.top(); suffix.push_back(str); s.pop(); } int main() { string nifix; stack<char>s; vector<string>suffix; cin >> nifix; for (int i = 0; i < nifix.size(); i++) { if (nifix[i] >= ‘0‘&&nifix[i] <= ‘9‘) { string str; while (nifix[i] >= ‘0‘&&nifix[i] <= ‘9‘) { str += nifix[i]; i++; } i -= 1; suffix.push_back(str); } else if (nifix[i] == ‘+‘ || nifix[i] == ‘-‘ || nifix[i] == ‘*‘ || nifix[i] == ‘/‘) { if (s.empty()) s.push(nifix[i]); else { if (higher(nifix[i], s.top())) s.push(nifix[i]); else { while (!s.empty() && !higher(nifix[i], s.top())) stack_vec(s, suffix); s.push(nifix[i]); } } } else if (nifix[i] == ‘(‘ || nifix[i] == ‘)‘) { if (nifix[i] == ‘(‘) s.push(nifix[i]); else { while (s.top() != ‘(‘) stack_vec(s, suffix); s.pop(); } } } while (!s.empty()) stack_vec(s, suffix); stringstream ss; stack<int>ca; int x,x1,x2; for (int i = 0; i < suffix.size(); i++) { if (suffix[i] == "+" || suffix[i] == "-" || suffix[i] == "*" || suffix[i] == "/") { x2 = ca.top(); ca.pop(); x1 = ca.top(); ca.pop(); switch (suffix[i][0]) { case ‘+‘:x = x1 + x2; break; case ‘-‘:x = x1 - x2; break; case ‘*‘:x = x1 * x2; break; case ‘/‘:x = x1 / x2; break; default:break; } ca.push(x); } else { ss << suffix[i]; ss >> x; ca.push(x); ss.clear(); } } cout << ca.top(); //system("pause"); return 0; }
以上是关于ALGO-156的主要内容,如果未能解决你的问题,请参考以下文章