原理:从左到右遍历表达式的每个数字和符号,遇到是数字就进栈,遇到是符号,就将处于栈顶两个数字出栈,进行运算,运算结果进栈,—直到最终获得结果。
举例:9 3 1-3*+ 10 2/+
#include <iostream>
#include <stack>
#include <vector>
#include <deque>
using namespace std;
char str[100][20];
int len = 0;
/*
*计算运算符的优先级
*/
int Grade(char ch)
{
if (ch == '*' || ch == '/')
return 2;
else if (ch == '+' || ch == '-')
return 1;
else return 0;
}
void Against()
{
stack<char>s;
printf("原算式:\n");
for (int i = 0;i < len; i++)
printf("%s ", str[i]);
printf("\n");
printf("转化成逆波兰表达式:\n");
//转化成逆波兰表达式
for (int i = 0; i < len; i++) {
//如果是数直接输出这个数
if (str[i][0] >= '0' && str[i][0] <= '9')
printf("%s ", str[i]);
else if (s.empty()) {
//栈为空时,直接把当前运算符入栈
s.push(str[i][0]);
}
//当运算符为左括号时,无条件入栈
else if (str[i][0] == '(')
s.push('(');
else if (str[i][0] == ')') {
/*
*当运算符为有括号时, 查看栈顶元素
*当栈顶元素不为左括号,出栈并输出
*当栈顶元素为左括号时,出栈
*/
while (1) {
char ch = s.top();
if (ch != '(') {
s.pop();
printf("%c ", ch);
}
else {
s.pop();
break;
}
}
}
else {
/*判断 +, -, *, /, 四种符号*/
while (1) {
//如果栈为空, 入栈
if (s.empty()) {
s.push(str[i][0]);
break;
}
/*
*比较当前运算符和栈顶运算符的优先级
*如果当前的大于栈顶的入栈
*否则出栈输出并继续比较
*/
char ch = s.top();
char operater = str[i][0];
if (Grade(operater) > Grade(ch)) {
//((operater == '*' || operater=='/') && (ch=='+' || ch=='-') || ch=='(')
//两种if条件都可以判断运算符的优先级
s.push(operater);
break;
}
else {
s.pop();
printf("%c ", ch);
}
}
}
}
while (!s.empty())
{
printf("%c ", s.top());
s.pop();
}
}
int main()
{
while (scanf_s("%s", str[len++]) != EOF);
len--;
Against();
}