#include<stdio.h>
#include<stdlib.h>
typedef struct Operandtype
{
double data;
char operator;
int type;
struct Operandtype *next;
}Operandtype,*Linkedlist;
typedef struct LinkedstackNode
{
double data;
struct LinkedstackNode *next;
}LinkedstackNode,*Linkedstack;
Linkedlist Init_Linkedlist() ;
Linkedstack Init_Linkedstack();
void calculate(Linkedstack s,char x);
void Push_Linkedstack(Linkedstack s,double x);
void Pop_Linkedstack(Linkedstack s, double *x);
void Push_Linkedlist(Linkedlist s,char x,Linkedlist p);
void evaluatePostfixExpression( Linkedlist expressList, double *result );
int main()
{ double *result=(double *)malloc(sizeof(double));
Linkedlist s=Init_Linkedlist();
Linkedlist p=s;
char x;
while(scanf("%c",&x))
Push_Linkedlist(s,x,p);/*输入中缀表达式数据 */
evaluatePostfixExpression(s,result);/*调用函数进行压栈出栈*/
if(*result)
printf("%.1lf", *result);/*输出结果8*/
else
printf("0.0");
return 0;
}
void Push_Linkedlist(Linkedlist s,char x,Linkedlist p)/*输入中缀表达式数据 */
{
Linkedlist L=(Operandtype *)malloc(sizeof(Operandtype));
if(x>='0'&&x<='9')
{
L->data=x-'0';
L->type=0;
}
else
{
L->operator=x;
L->type=1;
}
L->next=NULL;
p->next=L;
p=p->next;
}
Linkedlist Init_Linkedlist()//建立链栈
{
Operandtype *top=(Operandtype *)malloc(sizeof(Operandtype));
top->next=NULL;
return top;
}
void evaluatePostfixExpression( Linkedlist expressList, double *result )
{ Linkedlist F;
F=expressList->next;
Linkedstack top;
top=Init_Linkedstack();
while(F!=NULL)
{
if(F->type==0)
{
Push_Linkedstack(top,F->data);
}
else calculate(top,F->operator);
}
Pop_Linkedstack(top, result);
}
Linkedstack Init_Linkedstack()
{
LinkedstackNode *t=(LinkedstackNode *)malloc(sizeof(LinkedstackNode));
t->next=NULL;
return t;
}
void Push_Linkedstack(Linkedstack s,double x)
{
Linkedstack O;
O=(Linkedstack )malloc(sizeof(LinkedstackNode));
O->data=x;
O->next=s->next;
s->next=O;
}
void Pop_Linkedstack(Linkedstack s,double *x)
{
Linkedstack t;
t=s->next;
*x=t->data;
s->next=s->next->next;
free(t);
}
void calculate(Linkedstack s,char x)//运算
{
double a,b,result;
Pop_Linkedstack(s, &a);
Pop_Linkedstack(s, &b);
switch(x)
{
case '+':
result = b + a;
break;
case '-':
result = b - a;
break;
case '*':
result = b * a;
break;
case '/':
if(a)
result = b / a;
else
result = 0;
break;
}
Push_LinkedStack(s, result);
}