中缀表达式转后缀表达式
设立一个操作符栈,一个数组存放后缀表达式,从左到右扫描中缀表达式,如果是操作数则加入后缀表达式;如果是操作符则与栈顶元素比较优先级,规则为:(对于当前运算符)左括号一律入栈、右括号一串出栈、优先级高则入栈、小于等于一串出栈。
#include <iostream>
#include <string>
#include <stack>
#include <map>
#include <vector>
using namespace std;
map<string, int> pri;
void setPri() {
pri["#"] = 0;
pri["+"] = 1;
pri["-"] = 1;
pri["*"] = 2;
pri["/"] = 2;
}
string charToString(char c) {
string sc;
sc.push_back(c);
return sc;
}
vector<string> inToPost(string in) {
stack<string> op;
vector<string> post;
op.push("#");
string tmp = "";
for (int i = 0; i < in.size(); i++) {
if (in[i] >= '0' && in[i] <= '9') {
tmp += in[i];
}
else {
if (tmp != "") {
post.push_back(tmp);
tmp = "";
}
if (in[i] == '(') { //左括号一律入栈
op.push(charToString(in[i]));
}
else if (in[i] == ')') { //右括号一串出栈
while (op.top() != "(") { //括号中间的出栈到后缀表达式
string t