#include <iostream>#include <vector>#include <stack>#include <ctype.h>#include <cstdlib>#include <sstream>using namespace std;bool IsDigit(string str){ for(int i = 0; i < str.size(); i++) if ((str.at(i) > ‘9‘) || (str.at(i) < ‘0‘)) return false; return true;}int main(){ stack<string> s; vector<string> postfix; // 存放后缀表达式,作为求运算结果的输入 string input; while (cin >> input) { if (IsDigit(input)) //cout << input << ‘ ‘; postfix.push_back(input); else if (input == "(") s.push(input); else if (input == "+" || input == "-") { while ((!s.empty()) && (s.top() != "(")) { // 弹出优先级大于等于“+”“-”的运算符直到遇到“(” //cout << s.top() << ‘ ‘; postfix.push_back(s.top()); s.pop(); } s.push(input); } else if (input == "*" || input == "/") { // 在不知道栈是否为空时,不能top() while ((!s.empty()) && (s.top() != "(") && (s.top() != "+") && (s.top() != "-")) { // 弹出运算符“*”“/”直到遇到“(” //cout << s.top() << ‘ ‘; postfix.push_back(s.top()); s.pop(); } s.push(input); } else if (input == ")") { while ((!s.empty()) && (s.top() != "(")) { // 弹出直到遇到“(” //cout << s.top() << ‘ ‘; postfix.push_back(s.top()); s.pop(); } s.pop(); // 弹出“(” } else { // 遇到非法字符 cout << "Input illegal"; return -1; } } while (!s.empty()) { //cout << s.top() << ‘ ‘; postfix.push_back(s.top()); s.pop(); } vector<string>::iterator iter = postfix.begin(); for ( ; iter != postfix.end(); iter++) cout << *iter;#if 1 cout << endl; iter = postfix.begin(); while (iter != postfix.end()) { input = *iter; if (IsDigit(input)) s.push(input); else if ((input == "+") || (input == "-") || (input == "*") || (input == "/")) { int lhs = atoi((s.top()).c_str()); s.pop(); int rhs = atoi((s.top()).c_str()); s.pop(); stringstream ss; string midval; switch (*input.c_str()) { case ‘+‘ : ss << (lhs+rhs); ss >> midval; s.push(midval); break; case ‘-‘ : ss << (lhs-rhs); ss >> midval; s.push(midval); break; case ‘*‘ : ss << (lhs*rhs); ss >> midval; s.push(midval); break; case ‘/‘ : ss << (rhs/lhs); // 注意除法的操作数有顺序限制 ss >> midval; s.push(midval); break; } } iter++; } cout << s.top();#endif return 0;}
栈的应用 — 中缀式转后缀式,码迷,mamicode.com
原文地址:http://blog.csdn.net/nestler/article/details/24664793