向大神求助:为什么在输入7-2*3时会出现stack underflow,该如何更改?
# define StackSize 100#include<stdlib.h>
#include<string.h>
#include <stdio.h>
typedef int datatype;
typedef struct {
datatype data[StackSize];
int top;
} seqstack;
void initstack(seqstack *s)
{
s->top=0;
}
int stackempty(seqstack *s)
{
return(s->top==0);
}
int stackfull(seqstack *s)
{
return(s->top==StackSize);
}
void push(seqstack *s,datatype x)
{ if (stackfull(s))
{ printf("stack overflow!!");
exit(1);
}
s->data[s->top++]=x;
}
void pop(seqstack *s,datatype *e)
{ if(stackempty(s))
{ printf("stack underflow!");
exit(1);
}
s->top--;
*e=s->data[s->top];
}
datatype gettop(seqstack *s)
{
if(stackempty(s))
{ printf("stack is enpty!");
exit(0);
}
return (s->data[s->top-1]);
}
char op[]="+-*/()#";
int in(char c,char *op)
{ if(strchr(op,c))
return(1);
else
return(0);
}
int priority(char c)
{ /*将运算符转换成优先级,设置优先级用整型数表示:'#'其优先级为0;
'('其优先级为1;'+、-'其优先级为2
'*、/'其优先级为3;')'其优先级为4*/
switch(c)
{ case '#':return(0);
case '(':return(1);
case '+':
case '-': return(2);
case '*':
case '/': return(3);
case ')': return(4);
}
}
char precede(char c1,char c2)
{ /*pri1,pri2为栈顶运算符和当前运算符的优先级,比较2个运算符的优先级大小,
若pri1=1且pri2=4,返回=;
若pri1=0且pri2=0,返回=;若pri2=1,返回<;若pri2=4,返回>;若pri1>=pri2,返回>;
若pri1<pri2,返回<*/
int pri1,pri2;
pri1=priority(c1);
pri2=priority(c2);
if (pri1==1&&pri2==4) return('=');
if (pri1==0&&pri2==0) return('=');
if (pri2==1) return('<');
if (pri2==4) return('>');
if (pri1>=pri2) return('>');
if (pri1<pri2) return('<');
return('0');
}
int operate(int a,char theta,int b)
{/*计算a theta b 返回计算结果。注:theta为运算符*/
switch(theta)
{ case '+': return(a+b);
case '-':return(a-b);
case '*':return(a*b);
case '/':return(a/b);
}
}
char change(int c)
{/*将运算符栈弹出的内容转换成相应的运算符*/
switch(c)
{ case 35: return('#');
case 40: return('(');
case 41: return(')');
case 42: return('*');
case 43: return('+');
case 45: return('-');
case 47: return('/');
}
}
int evaluate(char *s)
{ /*算术表达式求值的算符优先算法。
设OPTR和OPND分别是运算符栈
和操作数栈,OP为运算符集合*/
char c,theta; int a,b,e;
int c1,c3,i=0,explen;
seqstack optr ,opnd;
initstack(&optr); push(&optr,35);
initstack(&opnd);
explen=strlen(s); /*求表达式的长度*/
while(s[i]!='#'||gettop(&optr)!=35)
{ c=s[i];
if(!in(c,op))
{ c1=c-48; /*将字符型数据转换成数字型数据*/
push(&opnd,c1);if(i<explen) i++;
}
else
{
switch(precede(gettop(&optr),c)) {
case '<': push(&optr,c); if(i<explen) i++;
break;
case '=': pop(&optr,&e);if(i<explen) i++;
break;
case '>': pop(&optr,&c1);
theta=change(c1);
pop(&opnd,&b);
pop(&opnd,&a);
push(&opnd,operate(a,theta,b));
break;
}
}
}
c1=gettop(&opnd);
/*destroystack(optr);
destroystack(opnd);*/
return c1;
}
int main()
{ int val,i;
char ss[80];
printf("\nExp: ");
scanf("%s",ss);
val=evaluate(ss);
printf("\nval=%d\n",val);
}