演算法分析
運算子優先順序
操作符 | # | ( | *,/ | +,- | ) |
---|---|---|---|---|---|
isp | 0 | 1 | 5 | 3 | 6 |
osp | 0 | 6 | 4 | 2 | 1 |
其中isp為棧內運算子優先順序,osp為棧外運算子優先順序。從表格可以看出,加減乘除運算的isp大於osp。
程式碼
//中綴表示式轉字尾
#include<iostream>
#include<string>
#include<stack>
using namespace std;
//棧內優先順序
int isp(char op) {
int priority = 0;
if (op == '#') {
priority = 0;
} else if (op == '(') {
priority = 1;
} else if (op == ')') {
priority = 6;
} else if (op == '*' || op == '/') {
priority = 5;
} else if (op == '+' || op == '-') {
priority = 3;
}
return priority;
}
//棧外優先順序
int icp(char op) {
int priority = 0;
if (op == '#') {
priority = 0;
} else if (op == '(') {
priority = 6;
} else if (op == ')') {
priority = 1;
} else if (op == '*' || op == '/') {
priority = 4;
} else if (op == '+' || op == '-') {
priority = 2;
}
return priority;
}
bool toRPN(string &str, string &str1) { //引用傳遞
stack<char> s; //定義一個char型別的棧s
s.push('#');
int i, isPri, icPri;
char c;
for (i = 0; i < str.size(); i++) {
c = str[i];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { //如果是數字,直接入棧
str1 += c;
} else {
isPri = isp(s.top());
icPri = icp(c);
while (isPri > icPri) {
str1 += s.top();
s.pop();
isPri = isp(s.top());
icPri = icp(c);
}
if (icPri > isPri) { //入棧
s.push(c);
} else if (icPri == isPri) { //直接退棧
s.pop();
}
}
}
while (!s.empty()) { //最後,如果棧不空,則彈出所有元素並輸出\
if(s.top() != '#'){
str1 += s.top();
}
s.pop();
}
return true;
}
int main() { //主程式
string from;
string to;
cout << "請輸入中綴表示式:" << endl;
cin >> from;
toRPN(from, to);
cout << "字尾表示式為:" << to << endl;
return 1;
}
執行結果
本作品採用《CC 協議》,轉載必須註明作者和本文連結