将中缀表达式转换成后缀表达式并输出,然后计算出后缀表达式的值。
程序:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"stack.h"
char* infix_to_postfix(char* str)
{
int i,j=0;
int SIZE=strlen(str);
if(str==NULL)
{
printf("empty string!!!\n");
return NULL;
}
Stack s=CreateStack(SIZE);
char *tmpstr=malloc(sizeof(char)*(SIZE+1));
if(tmpstr==NULL)
{
printf("tmpstr is empty!\n");
return NULL;
}
for(i=0;i<SIZE;++i)
{
if(str[i]=='+')
{
while(!IsEmpty(s) && Top(s)!='(' )
{
tmpstr[j++]=TopAndPop(s);
}
Push('+',s);
}
else if(str[i]=='-')
{
while(!IsEmpty(s) && Top(s)!='(' )
{
tmpstr[j++]=TopAndPop(s);
}
Push('-',s);
}
else if(str[i]=='*')
{
while(!IsEmpty(s) && (Top(s)=='*' || Top(s)=='/') )
{
tmpstr[j++]=TopAndPop(s);
}
Push('*',s);
}
else if(str[i]=='/')
{
while(!IsEmpty(s) && (Top(s)=='*' || Top(s)=='/') )
{
tmpstr[j++]=TopAndPop(s);
}
Push('/',s);
}
else if(str[i]=='(')
{
Push(str[i],s);
}
else if(str[i]==')')
{
while(Top(s)!='(')
{
tmpstr[j++]=TopAndPop(s);
}
Pop(s);
}
else
{
tmpstr[j++]=str[i];
}
}
while(!IsEmpty(s))
{
tmpstr[j++]=TopAndPop(s);
}
return tmpstr;
}
void compute(char *goal)
{
int i,pre,next,sum;
Stack s=CreateStack(strlen(goal));
if(s==NULL)
return ;
Push(goal[0],s);
Push(goal[1],s);
for(i=2;i<strlen(goal);++i)
{
switch(goal[i])
{
case '*':
{
pre=TopAndPop(s);
next=TopAndPop(s);
sum=(pre-'0')*(next-'0');
Push((char)(sum+'0'),s);
break;
}
case '/':
{
pre=TopAndPop(s);
next=TopAndPop(s);
sum=(next-'0')/(pre-'0');
Push((char)(sum+'0'),s);
break;
}
case '+':
{
pre=TopAndPop(s);
next=TopAndPop(s);
sum=(next-'0')+(pre-'0');
Push((char)(sum+'0'),s);
break;
}
case '-':
{
pre=TopAndPop(s);
next=TopAndPop(s);
sum=(next-'0')-(pre-'0');
Push((char)(sum+'0'),s);
break;
}
default:
{
Push(goal[i],s);
break;
}
}
}
printf("the result is : %d\n",(Top(s)-'0'));
}
int main()
{
char ss[]="1+2*3+(4*1+6)";
char* goal=infix_to_postfix(ss);
printf("the string is :%s\n",goal);
compute(goal);
return 0;
}
上面的程序有一个缺点,那就是只能得到sizeof(char)大小的计算结果,比如char为1个字节,那么表达式计算结果最大只能为256. 原因就在compute()函数中用的栈中的数组是char类型的。如果将infix_to_postfix()函数与compute()函数分开,写入不同的.c文件中,使他们调用的栈的数组分别为char和int类型的,那么就可以计算任意范围的表达式了。
转载于:https://blog.51cto.com/yuzwei/1685023