【综合】中缀表达式转换成后缀表达式后,用后缀表达式计算出结果

本文是把前两个文章的代码综合了起来,为了调理清楚一点,所以另开设了一篇博客(纯代码):

#include<stdio.h>
#include<malloc.h>
#define StackMaxSize 30
typedef struct stack
{
char a[StackMaxSize];
int top;
}STACK;
int Pre(char op)
{
switch(op)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
case '#':
default:
return 0;
}
}
char *Change(char *s1)    //中缀转换成后缀
{
STACK s;
int i=0,j=0;
char ch,*s2;
s2=(char *)malloc(sizeof(char));
s.top=-1;
s.a[++s.top]='#';
ch=s1[i++];
while(ch!='#')
{
if(ch=='(')        
{
s.a[++s.top]=ch;
ch=s1[i++];
}
else if(ch==')')
{
while(s.a[s.top]!='(')
{
s2[j++]=s.a[s.top--];
}
s.top--;
ch=s1[i++];
}
else if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
{
while(Pre(s.a[s.top])>=Pre(ch))
{
s2[j++]=s.a[s.top--];
}
s.a[++s.top]=ch;
ch=s1[i++];
}
else
{
s2[j++]=ch;
ch=s1[i++];
}
}
ch=s.a[s.top--];
while(ch!='#')
{
s2[j++]=ch;
ch=s.a[s.top--];
}
s2[j++]='#';
return s2;
}


int Pre(char *s1)           //后缀表达式的运算
{
int i=0;
int num1,num2,sum;
STACK S;
S.top=-1;
while(s1[i]!='#')
{
if(s1[i]>='0' && s1[i]<='9')
{
s1[i]-=48;          //因为现在是字符,所以要变成Int类型的值
S.a[++S.top]=s1[i];
}
else
{
num1=S.a[S.top--];  
num2=S.a[S.top--];
if(s1[i]=='+')
sum=num2+num1;
else if(s1[i]=='-')
sum=num2-num1;
else if(s1[i]=='*')
sum=num2*num1;
else if(s1[i]=='/')
sum=num2/num1;
S.a[++S.top]=sum;
}
i++;
}
printf("结果是:%d\n",S.a[S.top]);
return S.a[S.top];


}
void main()
{
int i=1,j=1;
char c,*s1,*s2;
s1=(char *)malloc(sizeof(char));
printf("请输入中缀表达式\n");
while((c=getchar())!='#')
{s1[i++]=c;}
s1[i]='#';
printf("\n");
s2=Change(s1);
printf("转换后的后缀表达式\n");
while(s2[j]!='#')
printf("%c",s2[j++]);
printf("\n");


Pre(s2);




}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值