表达式求值问题,新手求罩!!!!
#include<stdio.h>#include<stdlib.h>
#include<malloc.h>
#include<conio.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
char *top;
char *base;
int stacksize;
}Sqstack;
void Initstack(Sqstack *S)
{
S->base=(char *)malloc(STACK_INIT_SIZE*sizeof(char));
if(!S->base)
exit(-1);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
}
int StackEmpty(Sqstack *S)
{
if(S->top==S->base)
return 1;
else
return 0;
}
char GetTop(Sqstack *S)
{
char E;
if(StackEmpty(S))
return 0;
E=*S->top-1;
return E;
}
void Push(Sqstack *S,char e)
{
if(S->top-S->base>=S->stacksize)
{
S->base=(char*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(char));
if(!S->base)
exit(-1);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*S->top++=e;
}
void Pop(Sqstack *S,char *e)
{
if(S->top==S->base)
printf("ERROR!");
*e=*S->top--;
}
char Precede(char A,char B)
{
char a=A,b=B;
if((a=='+'||a=='-')&&(b=='+'||b=='-'||b==')'||b=='#'))
return '>';
else if((a=='+'||a=='-')&&(b=='*'||b=='/'||b=='('||b=='#'))
return '<';
else if((a=='*'||a=='/')&&(b=='*'||b=='/'||b==')'||b=='#'||b=='+'||b=='-'))
return '>';
else if((a=='*'||a=='/')&&b=='(')
return '>';
else if(a=='('&&(b=='*'||b=='/'||b=='('||b=='+'||b=='-'))
return '<';
else if(a=='('&&b==')')
return '=';
else if(a==')'&&(b=='*'||b=='/'||b==')'||b=='+'||b=='-'||b=='#'))
return '>';
else if(a=='#'&&(b=='*'||b=='/'||b=='('||b=='+'||b=='-'))
return '<';
else if(a=='#'&&b=='#')
return '=';
else
return '!';
}
int In(char e)
{
if(e=='+'||e=='-'||e=='*'||e=='/'||e=='('||e==')'||e=='#')
return 1;
else
return 0;
}
int Operate(int M,char F,int N)
{
if(F=='+')
return (N-48)+(M-48);
else if(F=='-')
return (N-48)-(M-48);
else if(F=='*')
return (N-48)*(M-48);
else if(F=='/')
return (N-48)/(M-48);
else return 0;
}
int evaluate(Sqstack *P)
{
char h=0,pl=0;
char X=0,Y=0,sum=0;
Sqstack Q;
Initstack(&Q);
while(P->top!=P->base)
{
Pop(P,&h);
Push(&Q,h);
}
while(Q.top!=Q.base)
{
Pop(&Q,&pl);
if(!In(pl))
Push(P,pl);
else{
Pop(P,&X);Pop(P,&Y);
Push(P,(char)Operate(X,pl,Y));
}
}
Pop(P,&sum);
return sum;
}
void Disp(Sqstack *S)
{
while(S->top!=S->base)
printf("%c",S->base++);
}
void Transexpression()
{
char ch,x=0,y=0;
Sqstack OPTR,HZ;
Initstack(&HZ);Initstack(&OPTR);
Push(&OPTR,'#');
ch=getchar();
while(ch!='#'||GetTop(&OPTR)!='#')
{
if(!In(ch))
{
Push(&HZ,ch);ch=getchar();
}
else
switch(Precede(GetTop(&OPTR),ch))
{
case '<':Push(&OPTR,ch);ch=getchar();break;
case '=':Pop(&OPTR,&x);ch=getchar();break;
case '>':Pop(&OPTR,&y);Push(&HZ,y);ch=getchar();break;
default :break;
}
}
Disp(&HZ);
}
void main()
{
printf("Please input exepression and endup with a '#':");
Transexpression();
}
[ 本帖最后由 long8855381 于 2014-4-2 22:38 编辑 ]