问题描述
- 栈的问题,用栈编写一个算术表达式求值
-
用栈做一个简单的算术运算,我觉得思想没问题,可是编译不过去,上网找了很多资料,觉得是栈的基本操作有问题,初始化有问题,可具体是什么错误我也不是很了解,求大神指教!!#include
#includetypedef struct
{
int data[100];
int top1;
}SqStack1;
typedef struct{
char suanfu[100];
int top2;
}SqStack2;
SqStack1 shuzi;
SqStack2 zifu;
char zcsuanfu;
int chushihua1(SqStack1 *shuzi)
{if((shuzi=(SqStack1*)malloc(sizeof(SqStack1)))==NULL)
return 0;
shuzi->top1=-1;
return 1;}
int chushihua2(SqStack2 zifu)
{
if((zifu=(SqStack2)malloc(sizeof(SqStack2)))==NULL)
return 0;
zifu->top2=0;
zifu->suanfu[0]='=';
return 1;
}
int panzhankong1(SqStack1 *shuzi)
{
if(shuzi->top1==-1)
return 1;
else return 0;
printf("判栈空1成功");
}
int panzhankong2(SqStack2 *zifu)
{
if(zifu->top2==-1)
return 1;
else return 0;
printf("判栈空2成功");
}int jinzhan1(SqStack1 *shuzi,int a)
{shuzi->top1++;
shuzi->data[shuzi->top1]=a;
return 1;
printf("数字进站成功");
}
int jinzhan2(SqStack2 *zifu,char a)
{zifu->top2++;
zifu->suanfu[zifu->top2]=a;
return 1;
printf("字符进站成功");
}
int chuzhan1(SqStack1 *shuzi,int *a)
{
if(panzhankong1(shuzi)) return 0;
*a=shuzi->data[shuzi->top1];
shuzi->top1--;
return 1;
}
int chuzhan2(SqStack2 *zifu,char *a)
{
if(panzhankong2(zifu)) return 0;
*a=zifu->suanfu[zifu->top2];
zifu->top2--;
return 1;
}
void suanfubijiao(char a,char b,SqStack1 *shuzi,SqStack2 *zifu)
{
void shuchujieguo(int i);
int i;switch(a)
{
case'+':
case'-':
if((b=='*')||(b=='/')||(b=='('))
i=1;
else i=3; break;
case'*':
case'/':
if(b=='(')
i=1;
else i=3; break;
case'(':
if(b=='=')
printf("输入有误");
else if(b==')')
i=2;
else i=1;break;
case')':
if(b=='(')
printf("输入有误");
else i=3;break;
case'=':
if(b=='=')
i=2;
else if(b==')')
printf("输入有误");
else i=1;break;
default:printf("有误");break;
}
shuchujieguo(i,shuzi,zifu);
}
void shuchujieguo(int i,SqStack1 *shuzi,SqStack2 *zifu)
{
int jisuanjieguo(int a,char ch,int b);
char ch;
int a,b,c;
if(i==3)
{chuzhan2(zifu,&ch);
chuzhan1(shuzi,&a);
chuzhan1(shuzi,&b);
c=jisuanjieguo(a,ch,b);
jinzhan1(shuzi,c);
suanfubijiao(zcsuanfu,zifu->suanfu[zifu->top2],shuzi,zifu);}
if(i==2)
{
chuzhan2(zifu,&ch);
}
if(i==1)
{
jinzhan2(zifu,zcsuanfu);
}
}
int jisuanjieguo(int a,char ch,int b)
{
int c;
switch(ch)
{
case'+':c=a+b;break;
case'-':c=a-b;break;
case'*':c=a*b;break;
case'/':c=a/b;break;
default:break;
}
return c;
}
void shuru(SqStack1 *shuzi,SqStack2 *zifu)
{
char d[100];
int i,sum=0;
printf("请输入算术表达式,=表示结束");
scanf("%s",d);
for(i=0;d[i]!='';i++)
{
if((d[i]>='0')&&(d[i]<='9'))
{sum=d[i]-'0';
jinzhan1(shuzi,sum);
}
else
{
zcsuanfu=d[i];
suanfubijiao(zcsuanfu,zifu->suanfu[zifu->top2],shuzi,zifu);
}
}}
void main()
{SqStack1 *s=&shuzi;
SqStack2 *z=&zifu;
chushihua1(s);
chushihua2(z);shuru(s,z);
printf("%d",s->data[s->top1]);}
用断点在进栈操作的时候就有问题。。。