Data structure Java implementation----Infix expression converted to a suffix expression
The main content of this article:
- Three forms of an expression
- infix expression and suffix expression conversion algorithm
One, three forms of expression:
- infix expression : The operator is placed in the middle of two operands, such as: (2+1). We always use infix expression when we do maths problem from childhood.
- postfix expression : Without parentheses, the operator is placed after two operands, and all calculations are performed in the order in which the operators appear, strictly from left to right (no longer consider precedence rules for operators), such as: 2 1 + 3 *. Another example is the suffix expression for 6-4/2 *5=23:3642/-5*+# (#符号为结束符)
- prefix expression : The same as the suffix expression, without parentheses, the operator is placed in front of two operands, such as: * + 2 1 3. prefix expressions and suffix expressions are almost the same, except that the symbolic positions are different, and the prefix expressions are not very common.
Second, infix expression conversion to suffix expression: (thinking)
1. Convert infix expression to suffix expression: (step, a bit difficult to understand)
(1) When the reading of the number is sent directly to the output queue;
(2) When the operator T is read:
A. Eject all operators with precedence above or equal to T in the stack and send them to the output queue;
Note: This sentence is not easy to understand, it can be said that, starting from the top of the stack, pop-up operators are higher precedence than the currently processed operators until a lower priority than it or encountered an opening parenthesis to stop .
b.t into the stack;
(3) When the opening parenthesis is read, it is always pressed into the stack;
(4) When the closing parenthesis is read, all the operators above the first opening parenthesis near the top of the stack are popped, sent to the output queue, and the left parenthesis is discarded;
(5) After all the infix expressions have been read, if there are still operators in the stack, they are sent to the output queue.
Example:
, the left column is the output sequence, and the column on the right is the stack.
2. Use suffix expression to calculate:
(1) build a stack s;
(2) Read the suffix expression from left to right, read the number to convert it to the value of the stack s, read the operator from the stack to pop up two numbers to Y and X, and then the "X operator Y" form the computer results, and then press the stack s;
(3) If the suffix expression is not read, repeat the above procedure, the final output stack at the top of the value is the end.
Example:
*6/3=-3 (2-5), followed by a prefix expression: 325-6*3/+. The results of the operation are as follows:
Code implementation: Converting infix expressions to suffix expressions
- The JDK Stack class uses
- Using generics
Code implementation:
(1) Stringtoarithmetic.java: ( A tool class that converts infix expressions to suffix expressions )
1/**2* Created by smyhvae on 2015/9/7.3* Tool Class:4* 1, infix expression conversion to suffix expression5* 2, give an arithmetic expression (infix expression), directly get the results of the calculation6*/78ImportJava.util.Stack;9ImportJava.util.regex.Pattern;1011PublicClassstringtoarithmetic {1213PrivateStringtoarithmetic () {14}1516//Methods: An arithmetic expression (infix expression) was given, and the result was obtained. For example (5+8+10) * *, return 2317PublicStaticDoubleStringtoarithmetic (String string) {18ReturnSuffixtoarithmetic (Infixtosuffix (string));19}2021st/**22* Infix expression-to-suffix expression handles only +,-, *,/and parentheses, does not handle the minus sign and other operators, and does not validate prefix expressions.23* To process the negative sign, the expression can be pre-escaped, and when the following conditions are true, the minus sign is replaced with a single-mesh operator "!" infix.charat[i]== '-' && (24* i==0| | infix.charat[i-1]== ' (')25* 3*6/4+326* 3+6-4 3 6 + 4-27* 6-4/2 3 6 4 2/-5 * +28*/29//Method: The infix expression is converted to a suffix expression30PublicStaticString Infixtosuffix (String infix) {Stack<character> Stack =New stack<character>();String suffix = "";33int length =Infix.length ();34for (int i = 0; i < length; i++) {35Character temp;36char C =Infix.charat (i);37Switch(c) {38//Ignore spaces39Case ':40Break;41//Touch ' (', push to stack42Case ' (':43Stack.push (c);44Break;45//Hit ' + '-' to eject all the operators in the stack and send them to the output queue46Case ' + ':47Case '-':48while (Stack.size ()! = 0) {temp =Stack.pop ();50if (temp = = ' (') {Wuyi Stack.push (' (');52Break;53}suffix + = "" +Temp55}56Stack.push (c);suffix + = "";58Break;59//Encounters ' * '/', pops all multiplication operators in the stack and sends them to the output queue60Case ' * ':61Case '/':62while (Stack.size ()! = 0) {temp =Stack.pop ();64if (temp = = ' (' | | temp = = ' + ' | | temp = = '-')) {65Stack.push (temp);66Break;67}Else{suffix + = "" +Temp69}70}71Stack.push (c);suffix + = "";73Break;74//A closing parenthesis is encountered, all the operators above the first opening parenthesis near the top of the stack are popped, sent to the output queue, and the left parenthesis is discarded75Case ') ':76while (Stack.size ()! = 0) {A. Temp =Stack.pop ();78if (temp = = ' (')79Break; -Else bayi suffix + = "+ temp; Suffix + + + ""; a break; 85//If the number is sent directly to the output sequence default:87 suffix + = c; 88} 89} 90 91//If the stack is not empty, the remaining operators are ejected in turn and sent to the output sequence. Stack.size ()! = 0) {suffix + = "+ Stack.pop (); 94} suffix return; 98/**100 * postfix101 *102 * @return double103 */104//method: Find out the arithmetic result by suffix expression public static double Suffixtoarithm Etic (String postfix) {106 107 pattern pattern = Pattern.compile ("\\d+| | (\\d+\\.\\d+) "); Use regular expressions to match numbers 108 String strings[] = Postfix.split (""); Converts a string into an array of strings 109 for (int i = 0; i < strings.length; i++) Strings[i].trim (); Remove the whitespace from the string 111 stack<double> Stack = new stack<double> (); 113 for (int i = 0; i < strings.length; i++) {strings[i].equals (")) continue;117 118//If it is a number, the stack 119 if ((Pattern.matcher (Strings[i])). Matches ()) { 121 Stack.push (double.parsedouble (strings[i])); 122} else {123//If it is an operator, the number of operations is popped, and the result is computed. 124 Double y = Stack.pop (), Double x = Stack.pop (); 126 Stack.push (CacuLate (x, Y, strings[i])); The result of the operation is re-pressed into the stack. 127}128}129 return Stack.pop (); The top element of the stack is the final result of the operation. 131}132 133 private static Double Caculate (double x, double y, String simble) {134 if (Simble.trim (). Equals ("+")) 135 return x + y;136 if (Simble.trim () Equals ("-")) 137 return x-y;138 if (Simble.trim (). Equals ("*")) 139 return x * y;140 if (Simble.trim (). Equals ("/")) 141 return x/y;142 return 0;143}144}
(2) Test.java: (Test Class)
1PublicClassTest {2PublicStaticvoidMain (string[] args) {3// 5 Span style= "color: #008080;" > 6 // call method: Infix expression to postfix expression System.out.println ( Stringtoarithmetic.infixtosuffix (str)); 9 // Call method: Give an arithmetic expression (infix expression), get the result 10 System.out.println ( Stringtoarithmetic.stringtoarithmetic (str)); 11 12 }13 14}
In the above code, the No. 07 line calculates the suffix expression based on the infix expression.
Line 10th: is to give an infix expression, directly to the results of the calculation, in fact, its steps are: first, according to infix expression to get the suffix expression, and then according to the suffix expression to calculate the result .
Operating effect:
Data structure Java implementation----Infix expression converted to a suffix expression