java数据结构与算法之中缀表达式转为后缀表达式的方法
本文实例讲述了java数据结构与算法之中缀表达式转为后缀表达式的方法。分享给大家供大家参考,具体如下:
//stack
publicclassStackX{
privateinttop;
privatechar[]stackArray;
privateintmaxSize;
//constructor
publicStackX(intmaxSize){
this.maxSize=maxSize;
this.top=-1;
stackArray=newchar[this.maxSize];
}
//putitemontopofstack
publicvoidpush(charpush){
stackArray[++top]=push;
}
//takeitemfromtopofstack
publiccharpop(){
returnstackArray[top--];
}
//peekthetopitemfromstack
publiccharpeek(){
returnstackArray[top];
}
//peekthecharacteratindexn
publiccharpeekN(intindex){
returnstackArray[index];
}
//trueifstackisempty
publicbooleanisEmpty(){
return(top==-1);
}
//returnstacksize
publicintsize(){
returntop+1;
}
}
//InToPost
publicclassInToPost{
privateStackXmyStack;
privateStringinput;
privateStringoutPut="";
//constructor
publicInToPost(Stringinput){
this.input=input;
myStack=newStackX(this.input.length());
}
//dotranslationtopostFix
publicStringdoTrans(){
for(inti=0;i<input.length();i++){
charch=input.charAt(i);
switch(ch){
case'+':
case'-':
this.getOper(ch,1);
break;
case'*':
case'/':
this.getOper(ch,2);
break;
case'(':
this.getOper(ch,3);
break;
case')':
this.getOper(ch,4);
break;
default:
this.outPut=this.outPut+ch;
}
}
while(!this.myStack.isEmpty()){
this.outPut=this.outPut+this.myStack.pop();
}
returnthis.outPut;
}
//getoperatorfrominput
publicvoidgetOper(charch,intprect1){
chartemp;
if(this.myStack.isEmpty()||prect1==3){
this.myStack.push(ch);
}
elseif(prect1==4){
while(!this.myStack.isEmpty()){
temp=this.myStack.pop();
if(temp=='(')continue;
this.outPut=this.outPut+temp;
}
}
elseif(prect1==1){
temp=this.myStack.peek();
if(temp=='(')this.myStack.push(ch);
else{
this.outPut=this.outPut+this.myStack.pop();
this.myStack.push(ch);
}
}
else{
temp=this.myStack.peek();
if(temp=='('||temp=='+'||temp=='-')this.myStack.push(ch);
else{
this.outPut=this.outPut+this.myStack.pop();
}
}
}
}
//Test
publicclassTestInToPost{
privatestaticInToPostinToPost;
privatestaticStringstr;
publicstaticvoidmain(String[]args){
str="((A+B)*C)-D";
inToPost=newInToPost(str);
System.out.println(inToPost.doTrans());
}
}
PS:算法实现不是很完善,有些复杂的表达式解析要出错,写出来做个纪念!
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。