写一个中缀表达式转后缀c++要求其中用到的函数名最短
这是一个使用栈数据结构将中缀表达式转换为后缀表达式的C++代码实现:
#include <iostream>
#include <stack>
using namespace std;
// 判断运算符的优先级
int precedence(char op) {
switch(op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
// 将中缀表达式转换为后缀表达式
string infixToPostfix(string infix) {
string postfix;
stack<char> opStack;
for (int i = 0; i < infix.length(); i++) {
char c = infix[i];
// 如果是字母或数字,直接添加到后缀表达式中
if (isalnum(c)) {
postfix += c;
}
// 如果是左括号,入栈
else if (c == '(') {
opStack.push(c);
}
// 如果是右括号,将栈顶的运算符弹出并添加到后缀表达式中,直到遇到左括号
else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix += opStack.top();
opStack.pop();
}
if (!opStack.empty() && opStack.top() == '(') {
opStack.pop();
}
}
// 如果是运算符,将栈顶的运算符弹出并添加到后缀表达式中,直到栈为空、遇到左括号或遇到优先级更低的运算符
else {
while (!opStack.empty() && precedence(opStack.top()) >= precedence(c)) {
postfix += opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
// 将栈中剩余的运算符弹出并添加到后缀表达式中
while (!opStack.empty()) {
postfix += opStack.top();
opStack.pop();
}
return postfix;
}
int main() {
string infix;
cout << "请输入中缀表达式:";
cin >> infix;
string postfix = infixToPostfix(infix);
cout << "后缀表达式为:" << postfix << endl;
return 0;
}
在此代码中,我们使用了precedence函数来判断运算符的优先级,用到了stack数据结构来实现栈,infixToPostfix函数用于将中缀表达式转换为后缀表达式
原文地址: https://www.cveoy.top/t/topic/ibCD 著作权归作者所有。请勿转载和采集!