题目描述
PIPI现在有若干个包含小写英文字母作为操作数 以及 ‘+’, ‘-’, '’, ‘/’, ‘^’ ,’(’,’)‘七种操作符的合法中缀表达式。请你将其转为后缀表达式(逆波兰式)。
PS:’'代表幂运算,23=8
输入
输入一个字符串s,表示中缀表达式。
输出
输出一个字符串表示对应的后缀表达式。
样例输入
a+bc+(de+f)g
样例输出
abc+def+g*+
// 题目:中缀表达式转后缀表达式 II
// 日期:2021/7/14
// 详情:有若干个包含小写英文字母作为操作数以及'+','-','*','/','^','(',')'五种操作符的合法中缀表达式。
// 请你将其转为后缀表达式(逆波兰式)。
// XWQ
#include <bits/stdc++.h>
using namespace std;
void Check(string str){
stack<char> op;
int priority[300];
priority['('] = 0; // 1.定义优先级
priority['+'] = priority['-'] = 1;
priority['*'] = priority['/'] = 2;
priority['^'] = 3;
for(int i=0; i<str.size(); i++){
if(str[i]>='a' && str[i]<='z'){
printf("%c", str[i]);
}
else{
if(op.empty()){
op.push(str[i]);
}
else if(str[i]=='('){
op.push(str[i]);
}
else if(str[i]==')'){ // 2*.比1291多了)步骤
while(!op.empty() && op.top()!='('){
printf("%c", op.top());
op.pop();
}
op.pop(); // 弹出左括号
}
else{
while(!op.empty() && priority[str[i]]<=priority[op.top()]){ // 2.使用优先级比较
printf("%c", op.top());
op.pop();
}
op.push(str[i]);
}
}
}
while(!op.empty()){
printf("%c", op.top());
op.pop();
}
}
int main(){
string str;
cin >> str;
Check(str);
}