算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+
、-
、*
、\
以及左右括号()
,表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
分析:
- 如果是操作数,直接输出
- 如果是操作符,如果栈空,直接压栈
- 如果栈不空,如果当前操作符优先级大于栈顶操作符优先级,压栈
- 如果当前操作符优先级小于等于栈顶操作符优先级,出栈
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
void print(){
static int flag=0;
if(flag) cout<<" ";
flag=1;
}
int main(){
//freopen("1.txt","r",stdin);
string str;
cin>>str;
stack<char>op;
for(int i=0;i<str.length();i++){
//处理运算数(此处的+、-表示正负,而非加减)
if((str[i]>='0'&&str[i]<='9')||((str[i]=='+'||str[i]=='-')&&(i==0||str[i-1]=='('))){
print();
if(str[i]!='+') cout<<str[i];
while(str[i+1]=='.'||(str[i+1]>='0'&&str[i+1]<='9'))
cout<<str[++i];
}
else{
if(str[i]==')'){//遇到右括号,则需要将左括号前的运算符全部弹栈输出
while(op.top()!='('){
print();
cout<<op.top();
op.pop();
}
op.pop();
}
else{
if(op.empty()) op.push(str[i]);//栈为空,无须比较,直接压栈
else{
while(!op.empty()&&op.top()!='('){
//比较优先级,如果str[i]的优先级大于栈顶运算符的优先级,直接压栈
if(str[i]=='('||((str[i]=='*'||str[i]=='/')&&(op.top()=='+'||op.top()=='-')))
break;
//如果str[i]的优先级小于等于栈顶的优先级,弹栈,之后再把str[i]压栈
print();
cout<<op.top();
op.pop();
}
op.push(str[i]);
}
}
}
}
//所有运算数均已操作完毕,最后将栈中剩余的操作符全部输出
while(!op.empty()){
print();
cout<<op.top();
op.pop();
}
return 0;
}