魔劣对大亚的解释:数据结构-栈的应用:中缀表达式转换为后缀表达式的算法、以及求后缀表达式值的算法

来源:百度文库 编辑:九乡新闻网 时间:2024/05/16 23:44:02

#define N 100
#include "stdio.h"
char exp[N];
void transfer()
{char str[N],stack[N];
int i=0,j,t,top=0; /*t作为exp的下标,top为stack的下标,i作为str的下标*/
str[i]=getchar();
while(str[i]!='#' && i   {i++;
str[i]=getchar();
   }
t=0;i=0;
while(str[i]!='#')
{if(str[i]>='0' && str[i]<='9')
exp[t++]=str[i];
else if(str[i]=='(')
stack[++top]=str[i];
else if(str[i]==')')
{while(top!=0 && stack[top]!='(')
     exp[t++]=stack[top--];
      top--;    /*‘(’出栈并抛弃*/
   }
else if(str[i]=='+'|| str[i]=='-')
{while(top!=0 && stack[top]!='(')
   exp[t++]=stack[top--];
   stack[++top]=str[i];
   }
else if(str[i]=='*'|| str[i]=='/')
   {while(top!=0 && (stack[top]=='*'|| stack[top]=='/'))
    exp[t++]=stack[top--];
stack[++top]=str[i];}
i++;
}
while(top!=0)
exp[t++]=stack[top--];
exp[t]='#';
for(j=0;jputchar(exp[j]);
printf("\n");
}

void compute()
{float stack[N],d;
int i=0,t=0,top=0;
transfer();
while(exp[t]!='#')
{if(exp[t]>='0' && exp[t]<='9')
    { d=exp[t]-'0';         /*将字符转换成对应的数值*/
         stack[++top]=d;
         }
   else
{switch(exp[t])
   {case '+':stack[top-1]= stack[top-1]+ stack[top];break;
    case '-':stack[top-1]= stack[top-1]- stack[top];break;
    case '*':stack[top-1]= stack[top-1]*stack[top];break;
    case '/':if(stack[top]!=0)
       {stack[top-1]= stack[top-1]/stack[top];
        break;}
       else
        {printf("\nChuShu is 0"); break;}
             }
    top--;
   }
   t++;
   }
printf("\nValue of Express=%f",stack[top]);
}
void main()
{compute();
getch();
}