中缀表达式转后缀表达式 并计算后缀表达式
#include <iostream> #include <vector> #include <stack> #include <string> int computeSuffixExp(char expression[], size_t len) { std::stack<int> dump; for (int i = 0; i < len; ++i) { if (isdigit(expression[i])) { dump.push(expression[i] - '0'); } else { int num1 = dump.top(); dump.pop(); int num2 = dump.top(); dump.pop(); int num3; switch (expression[i]) { case '+': num3 = num2 + num1; break; case '-': num3 = num2 - num1; break; case '*': num3 = num2 * num1; break; case '/': num3 = num2 / num1; break; } dump.push(num3); } } return dump.top(); } // ( >>> *、- >>> +、- void infixToSuffix(char exp[], char outExp[], int len) { std::stack<char> symbols; std::string output; for (int i = 0; i < len; ++i) { char cur = exp[i]; if (isdigit(cur)) output.push_back(cur); else { if (symbols.size() == 0) symbols.push(cur); else { if (cur == '-' || cur == '+') { char top = symbols.top(); while ((top == '*' || top == '/') && top != '(') { output.push_back(top); symbols.pop(); top = symbols.top(); } symbols.push(cur); } else if (cur == '(') { char top = symbols.top(); while (top != '(') { output.push_back(top); symbols.pop(); top = symbols.top(); } symbols.push(cur); } else if (cur == ')') { char top = symbols.top(); while (top != '(') { output.push_back(top); symbols.pop(); top = symbols.top(); } symbols.pop(); } else symbols.push(cur); } } } while (symbols.size() > 0) { output.push_back(symbols.top()); symbols.pop(); } strcpy_s(outExp, len, output.c_str()); } int main() { char infix[] = { '(','(','4','+', '5',')', '*', '6', '+', '7',')' ,'/', '6'}; char suffix[13]; infixToSuffix(infix, suffix, 13); int res = computeSuffixExp(suffix, strlen(suffix)); return 0; }