您的位置:首页 > 其它

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

2013-10-27 00:44 537 查看

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

#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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: