严蔚敏 吴伟明 数据结构 栈的基本操作实现 整数表达式求值
/*author.jiang.2010.5.12*/#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define STACK_INIT_SIZE 10
#define STACKIMCREMENT 2
typedef struct {
int *base;
int *top;
int stacksize;
}sqstack;
void initstack(sqstack *s)
{s->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
if(!s->base) exit(0);
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
}
void gettop(sqstack s,int *e)
{if(s.base==s.top) return;
*e=*(s.top-1);
}
void push(sqstack *s,int e)
{if(s->base-s->top>=s->stacksize)
{s->base=(int*)realloc(s->base,(s->stacksize+STACKIMCREMENT)*sizeof(int));
if(!s->base) exit(-2);
s->top=s->base+s->stacksize;
s->stacksize+=STACKIMCREMENT;
}
*s->top++=e;
}
void pop(sqstack *s,int *e)
{if(s->base==s->top) return;
*e=*--s->top;
}
char precede(char t1,char t2){
char f;
switch(t2){
case '+':
case '-':
if(t1=='('||t1=='#')
f='<';
else f='>';
break;
case '*':
case '/':
if(t1=='*'||t1=='/'||t1==')')
f='>';
else f='<';
break;
case '(':
if(t1==')'){
printf("error1\n");
exit(0);
}
else f='<';
break;
case ')':
switch(t1){
case '(':f='=';break;
case '#':{printf("error2\n");exit(0);}
default:f='>';
}
break;
case '#':
switch(t1){
case '(':{printf("error3\n");exit(0);}
case '#':f='=';
default:f='>';
}
break;
}
return f;
}
int in(char c){
switch(c){
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '#':return 1;
default:return 0;
}
}
int operate(int a,char theta,int b){
int c;
switch(theta){
case '+':c=a+b;break;
case '-':c=a-b;break;
case '*':c=a*b;break;
case '/':c=a/b;break;
}
return c;
}
int evaluateexpression(){
sqstack optr,opnd;
int a,b,i=0,x;
int d;
char c,theta;
char z[6];
initstack(&optr); push(&optr,'#');
initstack(&opnd);c=getchar();
gettop(optr,&x);
while(c!='#'||x!='#'){
if(in(c)){
switch(precede(x,c)){
case '<':
push(&optr,c);
c=getchar();
break;
case '=':
pop(&optr,&x);
c=getchar();
break;
case '>':
pop(&optr,&theta);
pop(&opnd,&b);
pop(&opnd,&a);
push(&opnd,operate(a,theta,b));
break;
}
}
else if(c>='0'&&c<='9'){
i=0;
do{z[i]=c;
i++;
c=getchar();
}while(c>='0'&&c<='9');
//z[i]=0;
d=atoi(z);
push(&opnd,d);
}
else{
printf("error4\n");
exit(0);
}
gettop(optr,&x);
}
gettop(opnd,&x);
return x;
}
void main(){
printf("input expressions end with '#'\n");
printf("------------------------------\n");
printf("reslut=%d\n",evaluateexpression());
printf("------------------------------\n");
}