感谢大佬博客的启发:https://blog.youkuaiyun.com/weixin_43906799/article/details/104561353
/*core:
1.只要是数字直接输出
2.若为符号:
①若栈顶的符号优先级高于或等于此时所需判断的符号优先级则循环弹出栈顶的元素
直到栈为空或栈顶的元素的优先级小于该符号的优先级
②若为'(' 则将该符号入栈,若为')'则将'()'之间的所有元素进行弹出
弹出时遵循①中的规则 ,且当为第一个'('后的第一个元素时,直接入栈
从第二个元素开始剩下的元素按照优先级进行出入栈
*/
#include<iostream>
#include<stack>
#include<cstdio>
#include<queue>
#include<string>
#include<map>
using namespace std;
map<char,int> priority;
void map_make(){ //根据符号的优先级做出优先级的map
priority['+'] = 1;
priority['-'] = 1;
priority['*'] = 2;
priority['/'] = 2;
priority['('] = 3;
priority[')'] = 3;
}
int main(){
stack<char> stk;
map_make();
string s;
getline(cin,s);
int time = 0; //空格控制变量
int len = s.length();
for(int i = 0;i < len;i++){
if((i == 0 || s[i - 1] == '(') && (s[i] == '+' || s[i] == '-') || (s[i] >= '0' && s[i] <= '9') ){//对数字的操作;去除数字前的符号
if(time == 0)time++; //control space
else cout<<" ";
if(s[i] != '+')cout<<s[i]; //ignore '+'
while(s[i + 1] == '.' || s[i + 1] >= '0' && s[i + 1] <= '9'){
i++; //judege float and other num
cout<<s[i];
}
}
else{
if(s[i] == '(')stk.push(s[i]);
else if(s[i] == ')'){
while(!stk.empty() && stk.top() != '('){
cout<<" "<<stk.top();
stk.pop();
}
stk.pop();
}
else {
while(!stk.empty() && stk.top() != '(' && priority[stk.top()] >= priority[s[i]]){
cout<<" "<<stk.top();
stk.pop();
}
stk.push(s[i]);
}
}
}
while(!stk.empty()){
cout<<" "<<stk.top();
stk.pop();
}
}