逆波兰式生成程序的java实现

内容:掌握语法分析的基本思想,并用高级语言编写逆波兰式生成程序;

要求:利用逆波兰式生成算法编写程序,将从键盘上输入的算术表达式(中缀表达式)转化成逆波兰式。

逆波兰表达式的生成过程涉及到运算符的优先级,下表中列出几个常用运算符的优先关系。

 

常用运算符优先关系矩阵

+

-

*

/

+

-

#define maxbuffer 64 void main() { char display_out(char out_ch[maxbuffer], char ch[32]); //int caculate_array(char out_ch[32]); static int i=0; static int j=0; char ch[maxbuffer],s[maxbuffer],out[maxbuffer]; cout<>ch; for(i=0;i<maxbuffer;i++) {out[i]=ch[i];} cout<<"请确认您输入的表达式: "; while(out[j]!='#') { cout<<out[j]; j++; } cout<<'#'<<endl; display_out(s,out); //caculate_array; } char display_out(char out_ch[32],char ch[]) { int top=-1; int i=0,data[maxbuffer],n; int j=0; char sta[20]; while(ch[i]!='#') { if(isalnum(ch[i])) { while(isalnum(ch[i])) { out_ch[j]=ch[i]; j++; i++; }out_ch[j]=' ';j++; } else{ switch(ch[i]) { case '+': case '-': if(sta[top]=='('||top==-1) { top++; sta[top]=ch[i]; i++; } else { //j--; out_ch[j]=sta[top]; j++; top--; //i++; } break; //break; case '*': case '/':if(sta[top]=='*'&&sta[top]=='/') { out_ch[j]=sta[top]; j++; //i++; top--; } else { top++; sta[top]=ch[i]; i++; } break ; //break; case '(':top++; sta[top]=ch[i]; i++; break; case ')':if(sta[top]=='(') { top--; i++; } if(top==-1) { cout<<"错误: 第"<<j<<"个位置的“)”没有找到与之匹配的“(”"; ch[i]='#';j=0; } else { //while(sta[top]!='('){ out_ch[j]=sta[top]; top--; j++; //}break; } break; /*case '#': out_ch[j]='#'; j++; break;*/ default: cout<<" your input is error"<<endl; ch[i]='#'; j=0; break; } } }while(top!=-1) { out_ch[j]=sta[top];j++; top--; } out_ch[j]='#'; n=0; cout<<"逆波兰表达式为: "; while(out_ch[n]!='#') { cout<<out_ch[n]; n++; } cout<<endl; j=0; /*while(ch[j]!='#') { top++; data[top]=ch[j]; } cout<<data[top]; */ return out_ch[maxbuffer]; } 逆波兰
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值