方法一:括号法(直接获得结果)
1、在运算符的两边加上括号
2、把符号移动到符号所在括号后边
3、去除所有括号
例:8*(3-1)—2/5
1、((8*(3-1))-(2/5))
2、((8(31)-)*(25)/)-
3、8 3 1 - * 2 5 / -
【2分钟秒杀-中缀表达式转前后缀表达式】 https://www.bilibili.com/video/BV1aV4y1771G/?share_source=copy_web&vd_source=d04bc972ba0b1aff78f14b3cdc972a6c
方法二:栈的应用
例:8*(3-1)-2/5
步骤(遍历字符串后进行判断)
1、数字直接加入逆波兰字符串
2、获得运算符时,判断栈不为空 且优先级不小于栈顶元素,就出栈,否则入栈
此时栈顶元素优先级高于当前元素,因此先出栈再入栈
3、左括号直接加入符号字符串
4、遇到右括号时,判断栈不为空并且栈顶不是(时,把符号放入逆波兰容器,同时出栈,遇到(,再把(出栈
5、当所有的中序表达式遍历完后,在栈内的符号依次出栈
6、拼接结果字符串
函数代码
#include <iostream>
#include <stack>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
//中缀表达式 3 + 2 * 2
//后缀表达式 3 2 2 * +
bool isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*'|| ch == '/';
}
int precedence(char op) {
if (op == '+' || op == '-')return 1;
if (op == '*' || op == '/')return 2;
return 0;
}
//将中缀表达式转换为逆波兰表达式
/*
1、数字直接加入逆波兰字符串
2、左括号直接加入符号字符串
3、遇到右括号时,判断栈不为空并且栈顶不是(时,把符号放入逆波兰容器,同时出栈,遇到(,再把(出栈
4、获得运算符时,判断栈不为空 且优先级不小于栈顶元素,就出栈,否则入栈
5、当所有的中序表达式遍历完后,在栈内的符号依次出栈
6、拼接结果字符串
*/
string infixToPostfix(const string& infix) {
stack<char>ops;
vector<char> postfix;
for (char ch : infix)
{
if (isspace(ch))continue;
if (isdigit(ch))
{
postfix.push_back(ch);
}
else if (ch =='(')
{
ops.push(ch);
}
else if (ch==')')
{
while (!ops.empty() && ops.top()!='(')
{
postfix.push_back(ops.top());
ops.pop();
}
//弹出‘(’
if (!ops.empty())
{
ops.pop();
}
}
else if (isOperator(ch))
{
while (!ops.empty() && precedence(ops.top()) >= precedence(ch))
{
postfix.push_back(ops.top());
ops.pop();
}
//栈为空或者优先级底就直接加入
ops.push(ch);
}
}
while (!ops.empty())
{
postfix.push_back(ops.top());
ops.pop();
}
string result;
for (char ch : postfix) {
result += ch;
}
return result;
}
int main() {
string infix = "8*(3-1)-2/5";
string postfix = infixToPostfix(infix);
cout << "Postfix expreesion:" << postfix << endl;
return 0;
}