//priority函数返回运算符的优先级
#include<stack>
#include<vector>
#include<string>
#include<iostream>
using namespace std;
int priority(char ch)
{
switch (ch)
{
case'(':
case')':
return 3;
case'*':
case'/':
return 2;
case'+':
case'-':
return 1;
dafault:
return -1;
}
}
string change(string data)
{
string temp;//存储数字字符串
string temp_null;
vector<string> lambda;//后缀表达式
stack<char>op;//运算符栈
string::iterator it = data.begin();
for (; it != data.end(); it++)//转换成后缀表达式,存在lambda中
{
if (*it == '-' && (it == data.begin() || *(it - 1) == '('))//如果是'-',且在开头或者'('之后,说明是负号(不是减号)
{
lambda.push_back("-");
}
else if (*it == '+' && (it == data.begin() || *(it - 1) == '('))//如果是‘+’,且在开头或者'('之后,则是正号,不是加号,不用管
;
else if (*it >= '0' && *it <= '9'||*it=='.')//如果是数字就放到temp里
{
if(*it!='0'&&*it!='.')//'0'和'.'要单独考虑,因为考虑 1.000 就是 1,这种情况不应该把多余的'0'和'.'放到temp里
temp += *it;
else if (*it == '.')//单独考虑‘.’
{
string::iterator ii = it + 1;
while (*ii == '0' && ii != data.end())
{
ii++;
}
if (ii != data.end() && *ii >= '1' && *ii <= '9')
temp += *it;
}
else if (*it == '0')//单独考虑‘0’
{
string::iterator ii = it;
while (*ii=='0' && ii!=data.end())
{
ii++;
}
if (ii != data.end() && ( * ii >= '1' && *ii <= '9'||*ii=='.'))
temp += *it;
}
if ((it + 1) == data.end() || (( * (it + 1) < '0' || *(it + 1) > '9') && *(it+1) != '.')) //数字读取结束
{
temp += ' ';
lambda.push_back(temp);//将结尾带‘ ’的数字字符串写入lambda
temp = temp_null;//将temp清空
}
}
else if (*it == '(')//如果是‘(’则入栈
{
op.push(*it);
}
else if (*it == ')')//如果是‘)’则将‘(’与‘)’之间所有运算符写入lambda,并将‘(’出栈
{
while (!op.empty() && op.top() != '(')
{
string te;//临时存储运算符
te += op.top();
te += ' ';
lambda.push_back(te);//运算符写入
op.pop();//更新
}
op.pop();
}
else if (op.empty() || priority(*it) > priority(op.top()))//如果优先级大于栈顶,则入栈
{
op.push(*it);
}
else if (op.empty() || priority(*it) <= priority(op.top()))//如果优先级小于等于栈顶,则将栈顶弹出并写入lambda,直至*it优先级大于栈顶或栈空或栈顶是‘(’,再将*it入栈
{
while (!op.empty() && op.top() != '(' && priority(*it) <= priority(op.top()))
{
string te;
te += op.top();
te += ' ';
lambda.push_back(te);
op.pop();
}
op.push(*it);
}
}
while (!op.empty())//读到结尾后,如果栈不为空,则弹出栈中所有元素并写入lambda
{
string te;
te += op.top();
te += ' ';
lambda.push_back(te);
op.pop();
}
string ttemp;//由于lambda最后一个元素的结尾的空格是多余的,所以应该去掉,ttemp存储去掉多余空格之前的后缀表达式
vector<string>::iterator it2 = lambda.begin();
int sign = 0;
for (; it2 != lambda.end(); it2++)
{
ttemp += *it2;
}
string ans;//最终结果
int n = ttemp.size() - 1;//不包括最后的空格
ans.assign(ttemp, 0, n);
return ans;
}
int main()
{
string data;
cin >> data;
cout << change(data);
return 0;
}