将一个中缀表达式转为一个后缀表达式。主要思想是遍历整个字符串数组,遇到字母直接输出,遇到运算符则放入一个栈中,若栈中已有元素,则再次遍历到运算符时应该将当前运算符与栈顶元素比较,若栈顶元素优先级高,则将栈顶元素输出并pop掉,使当前元素继续与新的栈顶元素进行比较。【特别需要注意的是】若当前元素与栈顶元素运算符优先级一样的时候,需要先将栈顶元素输出!例:A+B-C的后缀表达式为AB+C-,而不是我之前一直以为的ABC+-。注意了这个问题,这题感觉没什么难度了。
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
string s;
/*int n;
cin>>n;
while (n--) {*/
cin>>s;
int i = 0; // 计数
stack<char>store_string;
while (i < s.size()) {
if (s[i] >='a' && s[i]<= 'z' || s[i] >= 'A' && s[i] <= 'Z') {
cout<<s[i];
}
else if (s[i] == '+' || s[i] == '-') {
if (store_string.size() == 0) {
store_string.push(s[i]);
}
else if (!store_string.empty() && (store_string.top() == '+' || store_string.top() == '-' )) {
cout<<store_string.top();
store_string.pop();
store_string.push(s[i]);
}
else if (!store_string.empty() && (store_string.top() == '/' || store_string.top() == '*' || store_string.top() == '%')) {
while (!store_string.empty()) { // 若插入的运算符优先级比栈顶的小,则将栈内元素都输出
cout<<store_string.top();
store_string.pop();
}
store_string.push(s[i]);
}
}
else if (s[i] == '/' || s[i] == '*' || s[i] == '%') {
if (store_string.empty())
store_string.push(s[i]);
else {
while (!store_string.empty() && (store_string.top() == '/' || store_string.top() == '*' || store_string.top() == '%')) {
cout<<store_string.top();
store_string.pop();
}
store_string.push(s[i]);
}
}
i++;
}
while (store_string.size()) {
cout<<store_string.top();
store_string.pop();
}
//}
return 0;
}