转换原则:
1.当读到一个操作数时,立即将它放到输出中。操作符则不立即输出,放入栈中。遇到左圆括号也推入栈中。
2.如果遇到一个右括号,那么就将栈元素弹出,将符号写出直到遇到一个对应的左括号。但是这个左括号只被弹出,并不输出。
3.在读到操作符时,如果此时栈顶操作符优先性大于或等于此操作符,弹出栈顶操作符直到发现优先级更低的元素位置。除了处理)的时候,否则决不从栈中移走”(”。操作符中,+-优先级最低,()优先级最高。
4.如果读到输入的末尾,将栈元素弹出直到该栈变成空栈,将符号写到输出中。
源代码
#include <string>
#include <iostream>
#include <stack>
using namespace std;
int main() {
int number;
cin >> number;
while (number--) {
string str;
cin >> str;
stack<char> temp;
for (int i = 0; i < str.size(); ++i) {
if (str[i] == '+' || str[i] == '-') {
if (temp.size() != 0) {
while (temp.size() != 0 && temp.top()!='(') {
cout << temp.top();
temp.pop();
}
}
temp.push(str[i]);
//cout <<temp.size()<<endl;
}
else if (str[i] == '*' || str[i] == '/' || str[i] == '%') {
if (temp.size() != 0 && (temp.top() == '*' || temp.top() == '/' || temp.top() == '%')) {
cout << temp.top();
temp.pop();
}
temp.push(str[i]);
}
else if (str[i] == '(') {
temp.push(str[i]);
}
else if (str[i] == ')') {
while (temp.size() != 0 && temp.top() != '(') {
cout << temp.top();
temp.pop();
}
if (temp.size() != 0 && temp.top() == '(')
temp.pop();
}
else {
cout << str[i];
}
}
while (temp.size() != 0) {
cout << temp.top();
temp.pop();
}
cout << endl;
}
return 0;
}
后缀表达式求值
建立一个栈S 。从左到右读表达式,如果读到操作数就将它压入栈S中,如果读到n元运算符(即需要参数个数为n的运算符)则取出由栈顶向下的n项按操作符运算,再将运算的结果代替原栈顶的n项,压入栈S中 。如果后缀表达式未读完,则重复上面过程,最后输出栈顶的数值则为结束。
#include <iostream>
#include <stack>
#include <string>
#include <iomanip>
using namespace std;
int main() {
int number;
cin >> number;
while (number--) {
stack<double> oper;
string temp;
cin >> temp;
for (int i = 0; i < temp.size(); ++i) {
if ('a' <= temp[i] && temp[i] <= 'z') {
for (int j = 0; j < 26; ++j) {
if (temp[i] == 'a' + j) {
oper.push(1 + j);
break;
}
}
}
else if (temp[i] == '+') {
double a, b;
a = oper.top();
oper.pop();
b = oper.top();
oper.pop();
oper.push(a + b);
}
else if (temp[i] == '-') {
double a, b;
a = oper.top();
oper.pop();
b = oper.top();
oper.pop();
oper.push(b - a);
}
else if (temp[i] == '*') {
double a, b;
a = oper.top();
oper.pop();
b = oper.top();
oper.pop();
oper.push(a * b);
}
else if (temp[i] == '/') {
double a, b;
a = oper.top();
oper.pop();
b = oper.top();
oper.pop();
oper.push(b / a);
}
}
cout << fixed<<setprecision(2)<<oper.top() <<endl;
}
return 0;
}
/*注意哪个是a哪个是b*/