# 表达式转换（中缀表达式转为后缀表达式）

2+3*(7-4)+8/4

2 3 7 4 - * + 8 4 / +

#include<stdio.h>
#include<stdlib.h>
struct stack{
char *b;
int t;
};
int main()
{
int n,i,j,k,f=0;
char a[100];
struct stack *s=(struct stack *)malloc(sizeof(struct stack));
s->b=(char *)malloc(sizeof(char)*20);
s->t=-1;
gets(a);
for(i=0;a[i]!='\0';i++){
if((a[i]=='-'||a[i]=='+')&&(i==0||a[i-1]=='(')){//运算数前有正负号
if(f!=0) printf(" ");
else f=1;
if(a[i]=='-')printf("%c",a[i]);f=0;//f为0后面不输出空格
}

else if(a[i]>='0'&&a[i]<='9'){//是数字就输出，包括小数
if(f!=0) printf(" ");
else f=1;
while((a[i]>='0'&&a[i]<='9')||a[i]=='.'){
printf("%c",a[i]);
if((a[i+1]>='0'&&a[i+1]<='9')||a[i+1]=='.')i++;
else break;
}
}

else {
if(a[i]=='(') 	s->b[++(s->t)]=a[i];//左括号直接存入
else if(a[i]=='*'||a[i]=='/'){// 此时运算符是*或/时堆栈中优先级高的先计算
while(s->t!=-1&&s->b[s->t]=='*'||s->b[s->t]=='/') {
if(f!=0) printf(" ");
else f=1;
printf("%c",s->b[(s->t)--]);
}
s->b[++(s->t)]=a[i];//最后放入
}

else if(a[i]==')'){// 此时运算符是)时堆栈内容都取出来
while(s->b[s->t]!='(') {
if(f!=0) printf(" ");
else f=1;
printf("%c",s->b[(s->t)--]);
}
s->t--;//取出左括号
}

else if(a[i]=='+'||a[i]=='-'){// 此时运算符是+或-时括号之前的内容都取出来
while(s->t!=-1&&s->b[s->t]!='(') {
if(f!=0) printf(" ");
else f=1;
putchar(s->b[(s->t)--]);
}
s->b[++(s->t)]=a[i];
}
}
}

while(s->t!=-1) {//取出剩下的运算符
if(f!=0) printf(" ");
else f=1;printf("%c",s->b[(s->t)--]);
}
return 0;
}


04-09

04-14 3万+
08-06 1564
03-20 1万+
04-12 5万+
09-20 11万+
05-30 5万+
08-23 1211
10-01 1727
03-04 296
03-28 414
03-09 2万+
11-01 740