java數(shù)據(jù)結(jié)構(gòu)與算法之中綴表達式轉(zhuǎn)為后綴表達式的方法
本文實例講述了java數(shù)據(jù)結(jié)構(gòu)與算法之中綴表達式轉(zhuǎn)為后綴表達式的方法。分享給大家供大家參考,具體如下:
//stack public class StackX { private int top; private char[] stackArray; private int maxSize; //constructor public StackX(int maxSize){ this.maxSize = maxSize; this.top = -1; stackArray = new char[this.maxSize]; } //put item on top of stack public void push(char push){ stackArray[++top] = push; } //take item from top of stack public char pop(){ return stackArray[top--]; } //peek the top item from stack public char peek(){ return stackArray[top]; } //peek the character at index n public char peekN(int index){ return stackArray[index]; } //true if stack is empty public boolean isEmpty(){ return (top == -1); } //return stack size public int size(){ return top+1; } } //InToPost public class InToPost { private StackX myStack; private String input; private String outPut=""; //constructor public InToPost(String input){ this.input = input; myStack = new StackX(this.input.length()); } //do translation to postFix public String doTrans(){ for(int i=0; i<input.length(); i++){ char ch = 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(); } return this.outPut; } //get operator from input public void getOper(char ch, int prect1){ char temp; if(this.myStack.isEmpty()||prect1==3){ this.myStack.push(ch); } else if(prect1==4){ while(!this.myStack.isEmpty()){ temp = this.myStack.pop(); if(temp=='(')continue; this.outPut = this.outPut + temp; } } else if(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 public class TestInToPost { private static InToPost inToPost; private static String str; public static void main(String []args){ str = "((A+B)*C)-D"; inToPost = new InToPost(str); System.out.println(inToPost.doTrans()); } }
PS:算法實現(xiàn)不是很完善,有些復雜的表達式解析要出錯,寫出來做個紀念!
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
IDEA SpringBoot項目配置熱更新的步驟詳解(無需每次手動重啟服務(wù)器)
這篇文章主要介紹了IDEA SpringBoot項目配置熱更新的步驟,無需每次手動重啟服務(wù)器,本文通過圖文實例代碼相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04Java多線程的調(diào)度_動力節(jié)點Java學院整理
有多個線程,如何控制它們執(zhí)行的先后次序呢?下文給大家分享四種方法及java多線程調(diào)度的實例代碼,需要的朋友參考下吧2017-05-05