#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 100
char a[MAXSIZE];
char sp[MAXSIZE];
int main(){
char ch;
int i=0,now=0,top=-1;
while((ch=getchar())!='@'){
if(ch>='0' && ch<='9'){
a[++i]=ch;
if(a[i+1]<='0' || a[i+1]>='9'){
a[++i]=' ';
}
}else if(ch=='(' || ch==')' || ch=='+' || ch=='-' || ch=='/' || ch=='*'){
//a[++i]=' ';
switch(ch){
case ')':
while(sp[top]!='('){
a[++i]=sp[top];
top--;
a[++i]=' ';
}
top--;
break;
case '(':
sp[++top]=ch;
break;
case '+':
while(top!=-1 && sp[top]!='('){
a[++i]=sp[top];
top--;
a[++i]=' ';
}
sp[++top]='+';
break;
case '-':
while(top!=-1 && sp[top]!='('){
a[++i]=sp[top];
top--;
a[++i]=' ';
}
sp[++top]='-';
break;
case '*':
while(top!=-1 && sp[top]!='(' && sp[top]!='+' && sp[top]!='-'){
a[++i]=sp[top];
top--;
a[++i]=' ';
}
sp[++top]='*';
break;
case '/':
while(top!=-1 && sp[top]!='(' && sp[top]!='+' && sp[top]!='-'){
a[++i]=sp[top];
top--;
a[++i]=' ';
}
sp[++top]='/';
break;
}
}
}
while(top!=-1){
a[++i]=sp[top--];
a[++i]=' ';
}
for(int i=1;i<MAXSIZE;i++){
printf("%c",a[i]);
}
}
C语言:中缀转后缀表达式(极简版)
于 2023-02-02 21:15:57 首次发布