#include <iostream>
#include <stack>
using namespace std;
stack<char>s;
string str;
bool isnum(int &start)//判断从下标i起是否是一个num 判断不是一个数比较简单
{
if(str[start]=='+'||str[start]=='-')
{
if(start==0||start-1>=0&&str[start-1]=='(')//如果是加减号那么只有它是第一位或者它前面是左括号才可能是符号
{
start++;
while(isdigit(str[start])||str[start]=='.')//只要是数字或者有.就继续向后找
{
start++;//找到这个数的最后一个位置
}
return true;
}
}
else if(str[start]>='0'&&str[start]<='9')
{
while(isdigit(str[start])||str[start]=='.')//只要是数字或者有.就继续向后找
{
start++;//找到这个数的最后一个位置
}
return true;
}
else
return false;
}
int compare(char my,char your)//比较我的元素符优先级和栈顶运算符优先级 my的优先级大返回1 否则返回-1
{
if(your=='(')
return 1;
else if((my=='*'||my=='/')&&(your=='+'||your=='-'))
return 1;
else
return -1;
}
int main()
{
cin>>str;
int flag=1;
for(int i=0; i<str.size(); ++i)
{
int start=i;
if(isnum(start))//如果从当前位置开始是一个数 就把这个数输出 之后修改下标
{
if(flag==0)
{
cout<<" ";
}
for(int j=i; j<=start-1; ++j)
{
if(str[j]=='+')
continue;
else
cout<<str[j];
}
i=start-1;//回溯到上一个数因为待会儿有i++;
flag=0;
}
else if(str[i]=='(')
{
s.push('(');
}
else if(str[i]==')')//从栈中依次弹出元素直到遇到左括号
{
while(s.top()!='(')
{
cout<<" "<<s.top();
s.pop();
}
s.pop();//左括号也弹出
}
else //如果是运算符
{
if(s.empty())
s.push(str[i]);
else if(compare(str[i],s.top())==1)//优先级高于栈顶
{
s.push(str[i]);
}
else
{
while(!s.empty()&&compare(str[i],s.top())==-1)//只要栈顶元素的优先级高于或者等于我的元素就不断弹栈
{
cout<<" "<<s.top();
s.pop();
}
s.push(str[i]);
}
}
}
while(!s.empty())
{
cout<<" "<<s.top();
s.pop();
}
return 0;
}
/*
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
*/