求大神解决难题啊 ~~~~~~
实现算术表达式求值程序(栈的运用)设操作数:0,1,2,……,8,9(可扩充);
运算符:+,—,*,/,(,),#(#号为结束)。
输入中缀表达式,如:5+(4-2)*3 #,将其转换成后缀表达式:542-3*+#,
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
#include <string.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)
{
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 post[],char mid[])
{
int i=0,j=0;
char x;
slink S=(slink)malloc(sizeof(snode));
Push(&S,'#');
do
{
x=mid[i];
switch(x)
{
case '#' :
{
while(!Emptystack(S))
post[j]=Pop(&S);j++;
}break;
case ')' :
{
while(Getstop(S)!='(')
post[j]=Pop(&S);j++;
Pop(&S);
}break;
case '+' :
case '-' :
case '*' :
case '/' :
case '(' :
{
while(Precede(Getstop(S),x))
post[j]=Pop(&S);j++;
Push(&S,x);
}break;
}i++;
}while(x!= '#');
}
double postcount(char post[])
{
int i=0;
char x;
float z,a,b;
slink S=(slink)malloc(sizeof(snode));
while(post[i]!= '#')
{
x=post[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=post[i]- '0' ; Push(&S,x);
}
i++;
}
if(!Emptystack(S)) return(Getstop(S));
return 0;
}
void main()
{
char post[255],mid[255]=" ";
printf("请输入要处理的中缀表达式:\n",mid);
scanf_s("%s",mid);
printf("相应的后缀表达式为: \n","");
mid_post(post,mid);
printf( "%s\n",mid_post);
printf( "表达式的值为: %d",postcount(post));
getchar();
}