算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。 输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、/以及左右括号(),表达式不超过20个字符。 输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。 输入样例:
2+3*(7-4)+8/4 输出样例:
2 3 7 4 - * + 8 4 / +
#include <stdio.h> #include <stack> #include <string.h>#include <ctype.h>using namespace std; int main(){ stack<char> s; char k[50]={0}; char w[30]={0}; int y=0; gets(k); int flag=1,u=1; int e=0; int n=strlen(k); for(int i=0;i<n;i++){ if(isdigit(k[i])){ PRintf("%c",k[i]); w[y++]=k[i]; if(flag==0){ flag=1; } }else{ { if(k[i]=='.'){ printf("."); w[y++]='.'; }else if(k[i]=='('){ }else if((k[i-1]=='('||k[i-1]=='+'||k[i-1]=='-'||k[i-1]=='*'||k[i-1]=='/'||i==0)&&(k[i]=='+'||k[i]=='-')){ if(k[i]=='+'){ continue; }else{ printf("%c",k[i]); w[y++]=k[i]; continue; } }else if(flag==1){ printf(" "); w[y++]=' '; } flag=0; } if(k[i]=='('){ s.push(k[i]); flag=1; }else if(k[i]==')'){ while(s.top()!='('){ printf("%c ",s.top()); w[y++]=s.top(); s.pop(); } s.pop(); }else if(k[i]=='+'||k[i]=='-'){ while(!s.empty()&&s.top()!='('){ printf("%c ",s.top()); w[y++]=s.top(); s.pop(); } s.push(k[i]); }else if(k[i]=='*'||k[i]=='/'){ while(!s.empty()&&s.top()!='('&&s.top()!='+'&&s.top()!='-'){ printf("%c ",s.top()); w[y++]=s.top(); s.pop(); } s.push(k[i]); } } } while(!s.empty()){ if(w[y-1]==' '){ printf("%c",s.top()); w[y++]=s.top(); s.pop(); }else{ printf(" %c",s.top()); w[y++]=s.top(); s.pop(); } } return 0;}新闻热点
疑难解答