求高手指点,利用栈表达式求值的问题。循环不能结束?哪里错了?
问题:循环不能结束,一直输出‘#’。为什么?求高人指点迷津!代码如下
#include<stdio.h>
#include<malloc.h>
typedef struct linknode
{
char data;
float data1;
struct linknode *next;
}LiStack;
/*构造一个栈S*/
void InitStack(LiStack *&s)
{
s=(LiStack*)malloc(sizeof(LiStack));
s->next=NULL;
}
/*入栈*/
void Push (LiStack *&s,char e)
{
LiStack *p;
p=(LiStack *)malloc(sizeof(LiStack));
p->data=e;
p->next=s->next;
s->next=p;
}
/*出栈*/
int Pop(LiStack *&s,char &e)
{
LiStack *p;
if(s->next==NULL)
return 0;
p=s->next;
e=p->data; //注意不能更换顺序
s->next=p->next;
free(p);
return 1;
}
/*取栈顶元素*/
int GetTop(LiStack *s,char &e)
{
if(s->next==NULL)
return 0;
e=s->next->data;
printf("%c",e);
return 1;
}
/*入栈*/
void Push1 (LiStack *&s,float e)
{
LiStack *p;
p=(LiStack *)malloc(sizeof(LiStack));
p->data=e;
p->next=s->next;
s->next=p;
}
/*出栈*/
float Pop1(LiStack *&s,float &e)
{
LiStack *p;
if(s->next==NULL)
return 0;
p=s->next;
e=p->data; //注意不能更换顺序
s->next=p->next;
free(p);
return 1;
}
/*取栈顶元素*/
float GetTop1(LiStack *s,float &e)
{
if(s->next==NULL)
return 0;
e=s->next->data;
printf("%c",e);
return 1;
}
/*构造数组存储运算符号*/
char OP[7]={'+','-','*','/','(',')','#'};
/*开数组存储对运算符进行比较*/
char d[7][7]={ {'>','>','<','<','<','>','>'}, {'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'}, {'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=',' '}, {'>','>','>','>',' ','>','>'},
{'<','<','<','<','<',' ','='}
};
/*计算运算数*/
float Operate(float a, char theta, float b)
{
switch( theta )
{ case '+': return(a+b);
case '-': return(a-b);
case '*': return(a*b);
case '/': return(a/b);
default : return 0;
}
}
/*查找运算符是否相同*/
int In (char Test, char* Op)
{
for(int i=0; i<7; i++)
if(Test == Op[i])
return 1;
return 0;
}
/*比较运算符*/
char Precede(char a, char b)
{
int i, j;
for(i=0; i<7; i++)
if(a==OP[i])
break;
for(j=0; j<7; j++)
if(b==OP[j])
break;
return(d[i][j]);
}
/*计算表达式*/
float EvaluateExpression()
{
LiStack *OPTR,*OPND;
char c,e,theta;
float a,b,value;
InitStack(OPTR); Push(OPTR,'#');
InitStack(OPND); c=getchar();
while(c!='#'||GetTop(OPTR,e)!='#')
{
if(!In(c,OP))
{Push1(OPND,c); c=getchar();}
else
switch(Precede(GetTop(OPTR,e),c))
{ case '<': Push(OPTR,c); c=getchar(); break;
case '=': Pop(OPTR,e); c=getchar(); break;
case '>': Pop(OPTR,theta);
Pop1(OPND,b);
Pop1(OPND,a);
Push1( OPND,Operate(a,theta,b) );
break;
}
}
return GetTop1(OPND,value);
}
int main()
{
float value;
printf("请依次输入表达式:");
value=EvaluateExpression();
printf("计算表达式的结果:%.2f\n",value);
return 0;
}