给定一个中缀表达式,包含数字,(,),+,-,*,/中的若干种,以'#'作为结束,问你转换成后缀表达式是什么。 Input 第一行输入一个字符串s(1≤|s|≤20). Output 输出对应的后缀表达式,用空格隔开#include<bits/stdc++.h> using namespace std; int yxj[128],top=0; char st[25],s[25]; int main() { yxj['+']=1; yxj['-']=1; yxj['*']=2; yxj['/']=2; yxj['(']=-1; while(~scanf("%s",s)){ int i=0; int j=0; int w; if(s<=9&&s>=0)cout<<s<<" ";i++;//是数字,将其输出 else if(top=0&&s!<=9&&s!>=0)st[j]==s;i++;j++;top++;//栈中没有值,就直接将运算符放入 else if(s=='(')st[j]==s;i++;j++;top++;w=i;//当前是左括号,直接放入 else if(s==')'){ s=" ";; top--; j--; while(s==')'){ cout>>s<<" "; w++; j--; top--; } }//当前是右括号,取出栈顶的运算符直到左括号为止,并且将左括号弹出 else if(yxj[s]==2)st[j]==s;j++;i++;top++;//当前运算符优先级较高,直接放入 else { w=i; while(yxj[s]==2){ cout>>s<<" "; w++; j--; top--; } } //当前运算符优先级小于等于栈顶运算符优先级,则不断弹出栈顶运算符直到当前运算符优先级较高 } while(top);//结束后将栈中运算符输出 }
时间: 2024-04-17 12:29:06 浏览: 11
#include<bits/stdc++.h>
using namespace std;
int priority(char c) if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
} else {
return 0;
}
}
string infixToPostfix(string s) {
stack<char> stk;
string postfix = "";
stk.push('#');
int i = 0;
while (i < s.length()) {
if (isdigit(s[i])) {
while (i < s.length() && isdigit(s[i])) {
postfix += s[i];
i++;
}
postfix += " ";
} else if (s[i] == '(') {
stk.push('(');
i++;
} else if (s[i] == ')') {
while (stk.top() != '#' && stk.top() != '(') {
postfix += stk.top();
postfix += " ";
stk.pop();
}
if (stk.top() == '(') {
stk.pop();
}
i++;
} else {
while (stk.top() != '#' && priority(s[i]) <= priority(stk.top())) {
postfix += stk.top();
postfix += " ";
stk.pop();
}
stk.push(s[i]);
i++;
}
}
while (stk.top() != '#') {
postfix += stk.top();
postfix += " ";
stk.pop();
}
return postfix;
}
int main() {
string s;
cin >> s;
string postfix = infixToPostfix(s);
cout << postfix << endl;
return 0;
}