给定一个中缀表达式,包含数字,(,),+,-,*,/中的若干种,以'#'作为结束,问你转换成后缀表达式是什么。 Input 第一行输入一个字符串s(1≤|s|≤20). Output 输出对应的后缀表达式,用空格隔开c++
时间: 2024-04-17 22:25:28 浏览: 25
给定一个中缀表达式,要求将其转换为后缀表达式。下面是一个示例代码实现:
```cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
}
return 0;
}
string infixToPostfix(const string& s) {
string postfix;
stack<char> ops;
for (char c : s) {
if (c == ' ') {
continue;
} else if (c == '(') {
ops.push(c);
} else if (c == ')') {
while (!ops.empty() && ops.top() != '(') {
postfix += ops.top();
postfix += ' ';
ops.pop();
}
if (!ops.empty() && ops.top() == '(') {
ops.pop();
}
} else if (isdigit(c)) {
postfix += c;
postfix += ' ';
} else {
while (!ops.empty() && getPriority(c) <= getPriority(ops.top())) {
postfix += ops.top();
postfix += ' ';
ops.pop();
}
ops.push(c);
}
}
while (!ops.empty()) {
postfix += ops.top();
postfix += ' ';
ops.pop();
}
return postfix;
}
int main() {
string s;
cin >> s;
string postfix = infixToPostfix(s);
cout << postfix << endl;
return 0;
}
```
你可以将中缀表达式作为输入,程序会将其转换为后缀表达式并输出。后缀表达式的运算符之间使用空格进行分隔。
请注意,这段代码假定输入的中缀表达式中没有语法错误,并且运算符和操作数之间都使用了空格进行分隔。