Basic knowledge
Usually we say an arithmetic expression, for example: + (3-1) *3+10/2 is the infix expression , but the computer cannot calculate the value of infix expression, because the computer cannot perform the blending operation with the precedence of the left and right brackets and operators. The use of postfix expressions (also known as inverse Polish ) solves the above problem.
The suffix expression for the above arithmetic expression is: 9 3 1-3 * + 10 2/+
Algorithmic thinking
How do I calculate the result of the above suffix expression?
Answer: Scan the above suffix expression from left to right, and then:
1. Encountering numbers in the stack
2. The operator encounters the first two elements of the top of the stack, calculates the result, and adds the calculated result into the stack
3. Repeat 1 or 22 steps until only one element in the stack is the final result
Case code
In infix expressions: + (3-1) *3+10/2 as an example
To find the suffix expression and the final result code:
ImportJava.util.ArrayList;ImportJava.util.Stack;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern;/** * For suffix expression and operation result */ Public class Operators { PublicArraylist<string>Gethouzuibds(String expression) {//If infix expression: + + (3-1) *3+10/2 conversion to suffix expression 9 3 1-3 * + 2/+ ///idea: an operator stack s, which is output when the number is encountered, and a conditional stack is encountered by operator //If the current operator has a higher priority than the top element of the stack, the stack will be stacked otherwise. The current operator is then pushed into the stack //But when a closing parenthesis is encountered, the elements in the stack are stacked until the first opening parenthesis is matchedStack<string> Expstack =NewStack<string> (); Arraylist<string> Newexp =NewArraylist<string> ();//In the input string, insert a space in each character putting to make it easy to differentiate between one digit and multiple digitsstring[] Split = Expression.split (" "); for(inti =0; i < split.length; i++) {String s = split[i];if("(". Equals (s)) {Expstack.push (s); }Else if(")". Equals (s)) {String pops; while(!expstack.isempty ()) {pop = Expstack.pop ();if(Pop.equals ("(")) { Break; }Else{Newexp.add (POP); } } }Else if("+". Equals (s) | |"-". Equals (s) | |"*". Equals (s) | |"/". Equals (s)) {if(Expstack.isempty ()) {Expstack.push (s); }Else{String top = Expstack.peek ();if(Comparepro (S, top)) {//The current input operator s priority is higher than the precedence of the top of the upper stack operator, s into the stackExpstack.push (s); }Else{The operator s priority of the current input is not higher than the precedence of the top of the topmost operator, and will be lower or equal to the stack than the S-precedence while(!expstack.isempty ()) {String pop = Expstack.peek ();if(!comparepro (S, pop)) {Newexp.add (Expstack.pop ()); }Else{ Break; }} expstack.push (s); } } }Else{//Pure DigitalNewexp.add (s); } } while(!expstack.isempty ()) {Newexp.add (Expstack.pop ()); }returnNewexp; }/** * Compare priority, if inputoper priority is less than equal to Stopoperator return false, greater than return true * * @param inputoper * loss into operator * @param stopoperator * Stack top operator */ Public Boolean Comparepro(String inputoper, String stopoperator) {//If the top operator of the stack is the closest bracket, press the input operator directly on the stack if("(". Equals (Stopoperator)) {return true; }//If the operator of the current input is "+" or "-" and the top operator of the stack is "*" or "/", the input operators have a large precedence if(("*". Equals (Inputoper) | |"/". Equals (Inputoper)) && ("+". Equals (stopoperator) | |"-". Equals (Stopoperator)) {return true; }return false; }/*** Calculating the final result based on infix expression * / Public int GetResult(arraylist<string> expression) {Stack<integer> Resstack =NewStack<integer> (); for(String str:expression) {if(Str.matches ("\\d+") {Resstack.push (integer.valueof (str)); }Else{if(Resstack.isempty ()) {return-1; }//Stack not empty, take out the top two elements of the stack intTem1 = Resstack.pop ();intTEM2 = Resstack.pop ();intTemres =0;Switch(str) { Case "+": Temres = tem2 + tem1; Break; Case "-": Temres = tem2-tem1; Break; Case "*": Temres = tem2 * TEM1; Break; Case "/": Temres = tem2/tem1; Break; } resstack.push (Temres); } }if(resstack.size () = =1) {returnResstack.pop (); }Else{return-1; } }}
Main function Code:
Packagesuffix expression;ImportJava.util.ArrayList;/** * Suffix expression * / Public class Compute { Public Static void Main(string[] args) {Operators op =NewOperators (); String expression ="9 + (3-1) * 3 + 10/2"; arraylist<string> res = Op.gethouzuibds (expression); System.out.print ("suffix expression:"); for(String string:res) {System.out.print (string+" "); }intresult = Op.getresult (res); System.out.println (); System.out.println ("calculation result:"+result); }}
Results:
Suffix expression: 9 3 1-3 * + 10 2/+
Calculation Result: 20
Java version infix expression converted to a suffix expression and evaluated