题目分析:比较繁琐,因为符号和数字都要按字符处理,建议列一下顺序和各情况。
#include<stdio.h>
int top=-1;
char opChar[20];
void push(char c){
opChar[++top]=c;
}
char pop(void){
if(opChar[top]!='(')
printf(" %c",opChar[top]);
return opChar[top--];
}
int main()
{
char c;
int flag=0,firstOut=0;//刷新等式读取状态
while((c=getchar())!='\n')
{ //某段等式开头处 flag=0 时,不可能是“* / )”,那么不是‘(’,就一定是数字(可带“+-”符号)
if((flag==0&&c!='(')||(c>='0'&&c<='9'))
{
if(firstOut++) putchar(' ');
if(c!='+') putchar(c);
for (c = getchar(); (c>='0'&&c<='9')||c=='.'; c=getchar())
putchar(c);
ungetc(c,stdin);
flag=1;
}
else if(c=='('){//左括号直接压栈,并刷新状态
flag=0;
push(c);
}
else if (c==')')//右括号,一直出栈至左括号
{
while((c=pop())!='(');
}
else if (c=='+'||c=='-')//若 栈空 或 优先级大,才push
{
while(top!=-1&&opChar[top]!='(')//+-只比(优先级大,等到(才push
pop();
push(c);
}
else if (c=='*'||c=='/')//若 栈空 或 优先级大,才push
{
while(top!=-1&&(opChar[top]=='*'||opChar[top]=='/'))//避开自己,才push
pop();
push(c);
}
}
while (top!=-1)
pop();
return 0;
}