#include<stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<iostream>
using namespace std;
stack<char> op;
int flag;
int main(){
char stack[50];
char str[50];
scanf("%s", str);
int len = strlen(str);
for(int i = 0; i<len; i++){
if((str[i] == '+' || str[i] == '-') && (!i || str[i - 1] == '(') || (str[i] >= '0' && str[i] <= '9')){
if(!flag){
flag++;
}
else
cout<<" ";
if(str[i] != '+') putchar(str[i]);
while(str[i + 1] == '.' || (str[i + 1] >= '0' && str[i + 1] <= '9'))
putchar(str[++i]);
}
else{
//处理运算符
if(str[i] == ')'){//遇到右括号,则需要将左括号前的运算符全部弹栈输出
while(!op.empty() && op.top()!= '('){
cout<<" "<<op.top();
op.pop();
}
//如果栈不为空
if(!op.empty())
op.pop(); //左括号只弹栈,不输出
}
else {
if(op.empty()){ //栈为空,无须比较,直接压栈
op.push(str[i]);
continue;
}
//根据优先级顺序,压栈||(弹栈后压栈)
while(!op.empty() && op.top()!= '('){
//比较优先级,如果str[i]的优先级大于栈顶运算符的优先级,直接压栈
if(str[i] == '(' || ((str[i] == '*' || str[i] == '/') && (op.top() == '-' || op.top() == '+')))
break;
//如果str[i]的优先级小于栈顶的优先级,弹栈,之后再把str[i]压栈
cout<<" "<<op.top();
op.pop();
}
op.push(str[i]);
}
}
}
while(!op.empty()){ //所有运算数均已操作完毕,最后将栈中剩余的操作符全部输出
cout<<" "<<op.top();
//左括号不输出
op.pop();
}
return 0;
}
注意的地方就是 判断栈为空,将符号进栈的过程,其中要判断str[i]是不是’)’ ,如果是的话,有可能此时栈是空的,但是会将’)'进栈,结果出错。
参考文档:https://blog.csdn.net/op_mocun/article/details/105148288