算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
特殊情况:
1 + (-1) -> 1 -1 +
-1 -> -1
1 + (+1) -> 1 1 +
1.369 + 2.369 -> 1.369 2.369 +
#include<iostream>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<cstdio>
#include<string>
#include<stack>
#include<string>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
map<char,int> p;
struct Node{
double num;
char op;
bool flag;
};
typedef struct Node node;
stack<node> s;
queue<node> q;
void change(string str){
node temp;
for(int i = 0;i < str.length();){
if(str[i]=='('){
temp.flag = false;
temp.op = str[i];
s.push(temp);
i++;
}
else if(str[i]==')'){
while(!s.empty()&&s.top().op!='('){
q.push(s.top());
s.pop();
}
s.pop();
i++;
}
else if(str[i]>='0'&&str[i]<='9'){
temp.flag = true;
temp.num = str[i]-'0';
i++;
while(i<str.length()&&str[i]>='0'&&str[i]<='9'){
temp.num = temp.num*10 + (str[i]-'0');
i++;
}
if(str[i]=='.'){
i++;
int fnum,fnmb;
fnum = fnmb = 0;
while(i<str.length()&&str[i]>='0'&&str[i]<='9'){
fnum = fnum*10 + (str[i]-'0');
fnmb++;
i++;
}
temp.num += pow(0.1,fnmb)*fnum;
}
q.push(temp);
}
else if(str[i]=='-'){
if(i==0||str[i-1]=='('){
i++;
temp.flag = true;
temp.num = str[i]-'0';
i++;
while(i<str.length()&&str[i]>='0'&&str[i]<='9'){
temp.num = temp.num*10 + (str[i]-'0');
i++;
}
temp.num = -temp.num;
q.push(temp);
}
else{
temp.flag = false;
while(!s.empty()&&p[s.top().op]>=p[str[i]]){
q.push(s.top());
s.pop();
}
temp.op = str[i];
s.push(temp);
i++;
}
}
else if(str[i]=='+'){
if(i==0||str[i-1]=='('){
i++;
temp.flag = true;
temp.num = str[i]-'0';
i++;
while(i<str.length()&&str[i]>='0'&&str[i]<='9'){
temp.num = temp.num*10 + (str[i]-'0');
i++;
}
q.push(temp);
}
else{
temp.flag = false;
while(!s.empty()&&p[s.top().op]>=p[str[i]]){
q.push(s.top());
s.pop();
}
temp.op = str[i];
s.push(temp);
i++;
}
}
else{
temp.flag = false;
while(!s.empty()&&p[s.top().op]>=p[str[i]]){
q.push(s.top());
s.pop();
}
temp.op = str[i];
s.push(temp);
i++;
}
}
while(!s.empty()){
q.push(s.top());
s.pop();
}
}
int main()
{
node cur;
string str;
p['+'] = p['-'] = 1;
p['*'] = p['/'] = 2;
cin>>str;
change(str);
while(!q.empty()){
cur = q.front();
if (cur.flag == true) cout<<cur.num;
else cout<<cur.op;
q.pop();
if(!q.empty()) cout<<' ';
}
return 0;
}