帮忙给我改改这个万恶程序,谢谢!
求一个算数表达式的值,输入后先转化成后缀表达式输出,然后输出运算结果,我是用VC6.0编译的,有错误和警告,麻烦大家给改改,谢谢!
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
typedef struct node /*栈节点定义*/
{ char data;
struct node *next;
}snode,*slink;
int Emptystack(slink S) /*检测栈空*/
{ if(S==NULL) return(1);
else return(0);
}
char Pop(slink *top) /*出栈*/
{ char e;
slink p;
if(Emptystack(*top)) return(-1);
else
{ e=(*top)->data;
p=*top;*top=(*top)->next;
free(p);return(e);
}
}
void Push(slink *top,char e) /*进栈*/
{ slink p;
p=(slink)malloc(sizeof(snode));
p->data=e;
p->next=*top;
*top=p;
}
void Clearstack(slink *top) /*置空栈*/
{ slink p;
while(*top!=NULL)
{ p=(*top)->next;
Pop(top);
*top=p;
}
*top=NULL;
}
char Getstop(slink S) /*取栈顶*/
{ if(S!=NULL)return(S->data);
return(0);
}
int Precede(char x,char y) /*比较x是否“大于”y*/
{ switch(x)
{ case '(':x=0;break;
case '+':
case '-':x=1;break;
case '*':
case '/':x=2;break;
}
switch(y)
{ case '+':
case '-':y=1;break;
case '*':
case '/':y=2;break;
case '(':y=3;break;
}
if(x>=y)return(1);
else return(0);
}
void mid_post(char B[],char E[]) /*中缀表达式到后缀表达式的转换*/
{ int i=0,j=0;
char x;
slink S=NULL;
Push(&S,'#');
do
{ x=E[i++];
switch(x);
{ case '#':
{ while(!Emptystack(S))
B[j++]=Pop(&S);
}break;
case ')':
{ while(Getstop(S)!='(')
B[j++]=Pop(&S);
Pop(&S);
}break;
case '+':
case '-':
case '*':
case '/':
case '(':
{ while(Precede(Getstop(S),x))
B[j++]=Pop(&S);
Push(&S,x);
}break;
default:B[j++]=x;
}
}while(x!='#');
}
int postcount(char B[]) /*后缀表达式求值*/
{ int i=0;
char x;
float z,a,b;
slink S=NULL;
while(B[i]!='#')
{ x=B[i];
switch(x)
{ case '+':b=Pop(&S);a=Pop(&S);z=a+b;Push(&S,z);break;
case '-':b=Pop(&S);a=Pop(&S);z=a-b;Push(&S,z);break;
case '*':b=Pop(&S);a=Pop(&S);z=a*b;Push(&S,z);break;
case '/':b=Pop(&S);a=Pop(&S);z=a/b;Push(&S,z);break;
default:x=B[i]-'0';Push(&S,x);
}
i++;
}
if(!Emptystack(S)) return(Getstop(S));
}
void main()
{ char B[255],E[255]=" ";
printf("请输入要处理的中缀表达式:\n");
scanf("%s",E);
printf("相应的后缀表达式为:\n");
mid_post(B,E);
printf("%s\n",B);
printf("表达式的值为:%d",postcount(B));
getch();
}