用顺序栈实现算术表达式求值的代码问题
#include<stdio.h>
#include<stdlib.h>
#define n 100
typedef struct
{
char data[n];
int top;
}optr;//运算符栈
typedef struct
{
int data[n];
int top;
}opnd;//操作数栈
optr stachinit1(optr a) //运算符栈初始化
{
a.top=-1;
return a;
}
opnd stackinit2(opnd a) //操作数栈初始化
{
a.top=-1;
return a;
}
optr push1(optr a,char x) //将运算符压入栈中
{
if(a.top==n-1) {printf("栈满\n"); exit(0); }
a.top++;
a.data[a.top]=x;
return a;
}
opnd push2(opnd a,int x) //将操作数压入栈中
{
if(a.top==n-1) {printf("栈满\n"); exit(0); }
a.top++;
a.data[a.top]=x;
return a;
}
char stackgettop1(optr a) //取运算符栈栈顶元素
{
char x;
if(a.top==-1) {printf("栈空\n"); exit(0);}
x=a.data[a.top];
return x;
}
int stackgettop2(opnd a) //取操作数栈栈顶元素
{
int x;
if(a.top==-1) {printf("栈空\n"); exit(0);}
x=a.data[a.top];
return x;
}
char precede(char ah,char ch) //比较运算符的级别
{
if(ah>ch) return '>';
if(ah==ch) return '=';
if(ah<ch) return '<';
}
char pop1(optr a) //出运算符栈
{
char x;
if(a.top==-1) {printf("栈空\n"); exit(0);}
x=a.data[a.top];
a.top--;
return x;
}
int pop2(opnd a) //出操作符栈
{
int x;
if(a.top==-1) {printf("栈空\n"); exit(0);}
x=a.data[a.top];
a.top--;
return x;
}
int operate(int a,char x,int b) //运算
{
if(x=='+') return a+b;
if(x=='-') return a-b;
if(x=='/') return a/b;
if(x=='*') return a*b;
}
void main()
{
optr optr; //定义运算符栈
opnd opnd; //定义操作数栈
char ch,head,theat,q;
int x,y;
optr=stachinit1(optr); //初始化
optr=push1(optr,'#'); //'#'置于栈底,级别最低
opnd=stackinit2(opnd); //初始化
scanf("%c",&ch); //读入表达式,以'#'结束
while(!((ch=='#')&&(stackgettop1(optr)=='#')))
{ if(ch>='0'&&ch<='9') //若读入的字符为数字,存入操作数栈
{
opnd=push2(opnd,ch); scanf("%c",&ch);
}
q=precede(head,ch); //若为运算符,入运算符栈
{ //比较操作符ch和栈顶操作符head
if (q=='<') //级别高,入栈
{
optr=push1(optr,ch);
scanf("%c",&ch);
}
if(q=='=') //删除括号
{
pop1(optr);
scanf("%c",&ch);
}
if(q=='>')
{
theat=pop1(optr); //级别低,弹出一个运算符
x=pop2(opnd); y=pop2(opnd); //弹出两个操作数
opnd=push2(opnd,operate(y,theat,x)); //进行相应运算,结果入栈
scanf("%c",&ch);
}
}
}
printf("%d",stackgettop2(opnd)); //输出表达式运算结果
}
实在找不出错,请教一下