中缀表达式转后缀c++
中缀表达式转后缀表达式的算法主要包括以下步骤:
-
创建一个空栈S和一个空字符串result。
-
从左到右遍历中缀表达式的每个字符:
-
如果遇到操作数,直接将其添加到result中。
-
如果遇到运算符,判断栈顶运算符的优先级:
-
如果栈为空或者栈顶为左括号"(",则直接将运算符入栈。
-
如果当前运算符优先级大于栈顶运算符,则直接将运算符入栈。
-
如果当前运算符优先级小于等于栈顶运算符,则将栈顶运算符弹出并添加到result中,直到栈顶运算符优先级小于当前运算符或者栈为空,然后将当前运算符入栈。
-
-
如果遇到左括号"(",直接将其入栈。
-
如果遇到右括号")",则将栈顶运算符弹出并添加到result中,直到遇到左括号"(",然后将左括号弹出,但不将其添加到result中。
-
-
遍历完中缀表达式后,将栈中剩余的运算符依次弹出并添加到result中。
-
返回result作为后缀表达式。
以下是一个实现中缀表达式转后缀表达式的C++代码示例:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getPriority(char op) {
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
else
return 0;
}
string infixToPostfix(string infix) {
stack<char> s;
string postfix;
for (int i = 0; i < infix.length(); i++) {
char c = infix[i];
if (isalnum(c)) {
postfix += c;
} else if (c == '(') {
s.push(c);
} else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop(); // 弹出左括号
} else {
while (!s.empty() && getPriority(c) <= getPriority(s.top())) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix = "a+b*(c-d)+e/f";
string postfix = infixToPostfix(infix);
cout << "Postfix: " << postfix << endl;
return 0;
}
上述代码将中缀表达式"a+b*(c-d)+e/f"转换为后缀表达式"abcd-*+ef/+",并输出结果
原文地址: https://www.cveoy.top/t/topic/h6To 著作权归作者所有。请勿转载和采集!