关于栈的应用之表达式求值,大家看看指教一下问题
表达式的计算,运行有一个问题,请问这是为什么呢采用中序的方法
#include<stdio.h>
#include<malloc.h>
typedef struct node1{
char elem;
struct node1*next;
}elemstack;
typedef struct node2{
int data;
struct node2*next;
}datastack;
elemstack *build(elemstack*L) //输入表达式
{
elemstack*head,*p,*s;
char ch;
L=head=(elemstack*)malloc(sizeof(elemstack));
p=head;
head->next=NULL;
ch=getchar();
while(ch!='#')
{
s=(elemstack*)malloc(sizeof(elemstack));
s->elem=ch;
p->next=s;
p=s;
ch=getchar();
}
s=(elemstack*)malloc(sizeof(elemstack));
s->elem=ch;
p->next=s;
p=s;
p->next=NULL;
return L;
}
datastack *datapush(datastack*top1,int x) //数字入栈
{
datastack*s;
s=(datastack*)malloc(sizeof(datastack));
s->data=x;
s->next=top1;
top1=s;
return top1;
}
int datapop(datastack*top1,int x) //数字出栈
{
datastack*s;
x=top1->data;
s=top1;
top1=top1->next;
free(s);
return x;
}
elemstack *elempush(elemstack*top2,char ch) //运算符入栈
{
elemstack*s;
s=(elemstack*)malloc(sizeof(elemstack));
s->elem=ch;
s->next=top2;
top2=s;
return top2;
}
int elempop(elemstack*top2,char ch) //运算符出栈
{
elemstack*s;
ch=top2->elem;
s=top2;
top2=top2->next;
free(s);
return ch;
}
int level(char ch) //比较运算符的优先级
{
if(ch=='+'||ch=='-')return 1;
else if(ch=='*'||ch=='/')return 2;
else if(ch=='#')return 0;
else if(ch=='(')return -1;
}
int main( )
{
datastack*top1;
elemstack*top2,*p,*L;
int i,a,b,c;
float n;
char ch;
top1=NULL;
top2=NULL;
build(L);
p=L->next;
while(p)
{if(p->elem=='(') //左括号时直接进栈
{elempush(top2,p->elem);
p=p->next;}
else if(p->elem>'0'&&p->elem<'9') //数字进入数字栈
{i=p->elem-'0';
datapush(top1,i);
p=p->next;}
else if(level(p->elem)>level(top2->elem)) //如果运算符的优先级大于运算符栈栈顶运算符,当前运算符就进栈
{elempush(top2,p->elem);
p=p->next;}
else if(level(p->elem<=level(top2->elem)||p->elem==')')) //否则进行计算
{datapop(top1,b);
datapop(top1,a);
elempop(top2,ch);
switch(ch){
case '+': c=a+b;break;
case '-': c=a-b;break;
case '*': c=a*b;break;
case '/': c=a/b;break;
}
datapush(top1,c);
}
else if(p->next==')'&&top2->elem=='(')
{free(top2);
p=p->next;}
}
n=datapop(top1,top1->data);
printf("%f",n);
}