#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
int y,z;
char theta;
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)
printf("内存分配错误");
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
}
void Push(Sqstack *S,int e)
{
if(S->top-S->base >= S->stacksize)
{
S->base = (int *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(int));
if(!S->base)
printf("从新分配内存错误");
S->top = S->base+S->stacksize;
}
*S->top++ = e;
}
int Gettop(Sqstack *S)
{
if(S->top == S->base)
printf("栈已经为空,无法执行!");
return *(S->top-1);
}
int Pop(Sqstack *S)
{
if(S->top==S->base)
printf("ERROR\n");
return *--S->top;
}
/*
*若为空则返回1 否则返回0
*/
int Isempty(Sqstack s)
{
if( s.top == s.base )
return 1;
return 0;
}
char Precede(char a1,char a2)//a1 in, a2 out
{
if( (a1=='+'||a1=='-') && (a2=='+'||a2=='-'||a2==')' || a2=='#' ))
return '>';//pop
else if( (a1=='+'||a1=='-') && (a2=='*'||a2=='/'||a2=='('))
return '<';//push
else if((a1=='*'||a1=='/')&&(a2=='+'||a2=='-'||a2=='*'||a2=='/'||a2==')'||a2=='#'))
return '>';//pop
else if((a1=='*'||a1=='/') && a2=='(')
return '<';
else if(a1=='('&&(a2=='+'||a2=='-'||a2=='*'||a2=='/'))
return '
<';
else if(a1=='('&&a2==')')
return '=';
//
else if(a1==')'&&(a2=='+'||a2=='-'||a2=='*'||a2=='/'||a2==')'||a2=='#'))
//
return '>';
else if(a1=='#'&& (a2=='+'||a2=='-'||a2=='*'||a2=='/'||a2=='(') )
return '<';
else if(a1=='#' && a2=='#')
return '=';
else
return(0);
}
int Operate(int n,char c,int m)
{
if(c=='+') return(n+m);
else if(c=='-') return(n-m);
else if(c=='*') return(n*m);
else if(c=='/') return(n/m);
else return(0);
}
void main()
{
Sqstack OPND, OPTR;
int a = 0;
Initstack(&OPND);//operand stack
Initstack(&OPTR);//operator stack
Push(&OPTR,'#');
char c;
c = getchar();
//
while(c!='#'||Gettop(&OPTR)!='#')
while ( !Isempty(OPTR) )
{
a = 0;//initialize variable a
while(c>='0' && c<='9')
{
a = a*10 + c - '0';
c = getchar();
};
if( 0 != a )
Push(&OPND,a);
else
switch(Precede(Gettop(&OPTR),c))
{
case '<'://栈顶元素优先权低
Push(&OPTR,c);
c=getchar();break;
case '='://脱括号并接受下一字符
Pop(&OPTR);
c=getchar();
break;
case '>'://退栈并将运算结果入栈
theta = Pop(&OPTR);
//y=Pop(&OPND);z=Pop(&OPND);
z = Pop(&OPND); y = Pop(&OPND);
Push(&OPND,Operate(y,theta,z));
break;
default:break;
}
}
printf("\n结果是:%d",Gettop(&OPND));
}