算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
using namespace std;
map<char,int>m={{'(',0},{')',0},{'+',1},{'-',1},{'*',2},{'/',2}};
int main() {
string s;
cin>>s;
stack<char>st;
int flag=1;
for(int i=0;i<s.size();i++){
if(isdigit(s[i])||s[i]=='.'||((!i||s[i-1]=='(')&&(s[i]=='+'||s[i]=='-'))){
if(!flag) cout<<" ";
else flag=0;
if(s[i]!='+') cout<<s[i];
while(s[i+1]=='.'||isdigit(s[i+1])){
cout<<s[++i];
}
}
else{
if(s[i]=='('){
st.push(s[i]);
}
else if(s[i]==')'){
while(st.top()!='('){
cout<<" "<<st.top();
st.pop();
}
st.pop();
}
else{
while(st.size()&&m[s[i]]<=m[st.top()]){
cout<<" "<<st.top();
st.pop();
}
st.push(s[i]);
}
}
}
while(st.size()){//将栈中剩余的放入数组
cout<<" "<<st.top();
st.pop();
}
return 0;
}
#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
using namespace std;
map<char,int>m={{'(',0},{')',0},{'+',1},{'-',1},{'*',2},{'/',2}};
int main() {
string s;
cin>>s;
stack<char>st;
vector<string>v;
string temp;
for(int i=0;i<s.size();i++){
if(isdigit(s[i])||s[i]=='.'||((!i||s[i-1]=='(')&&(s[i]=='+'||s[i]=='-'))){
if(s[i]!='+') temp={s[i]};
else temp="";
while(s[i+1]=='.'||isdigit(s[i+1])){
temp+=s[++i];
}
v.push_back(temp);
}
else{
if(s[i]=='('){
st.push(s[i]);
}
else if(s[i]==')'){
while(st.top()!='('){
v.push_back({st.top()});
st.pop();
}
st.pop();
}
else{
while(st.size()&&m[s[i]]<=m[st.top()]){
v.push_back({st.top()});
st.pop();
}
st.push(s[i]);
}
}
}
while(st.size()){
v.push_back({st.top()});
st.pop();
}
for(int i=0;i<v.size();i++){
if(!i){
cout<<v[i];
}
else{
cout<<" "<<v[i];
}
}
return 0;
}