C++ 中缀表达式转后缀表达式代码示例
下面是一个使用栈实现的中缀表达式转后缀的 C++ 代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getPriority(char c) {
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
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(s.top()) >= getPriority(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix;
cout << '请输入中缀表达式:';
cin >> infix;
string postfix = infixToPostfix(infix);
cout << '后缀表达式为:' << postfix << endl;
return 0;
}
这个代码中使用了一个 getPriority 函数来获取运算符的优先级,其它函数名尽量使用了最简短的名称。
原文地址: https://www.cveoy.top/t/topic/pUlg 著作权归作者所有。请勿转载和采集!