Calculation of postfix expressions
Algorithm Description:
1. When two components are encountered, they are pressed into the stack.
2. When the operator is encountered, it takes two components from the stack, calculates the result, and presses the result into the stack.
Specific implementation:
1 Private StaticStack<double> stack=NewStack<double>();2 Public voidCalcufix (Charexpr) {3 Doubleleft=0.0;4 Doubleright=0.0;5 if(Get2opreate ()) {6right=Stack.pop ();7left=Stack.pop (); 8 }9 Switch(expr) {Ten Case+: OneStack.add (Left+right); Break; A Case‘-‘: -Stack.add (Left-right); Break; - Case‘*‘: theStack.add (Left*right); Break; - Case‘/‘: -Stack.add ((Double) left/right); Break; - Case^: +Stack.add (Math.pow (left, right)); Break; - } + } A at PublicBoolean get2opreate () { -Boolean result=false; - if(Stack.size () >=2){ -result=true; - } - returnresult; in } - to Public Static voidMain (String[]args) { +Postfix fix=Newpostfix (); -Scanner sc=NewScanner (system.in); theString line=Sc.next (); * Char[] list=Line.tochararray (); $ for(inti=0;i<list.length;i++){Panax Notoginseng if(list[i]== ' + ' | | list[i]== '-' | | list[i]== ' * ' | | list[i]== '/' | | list[i]== ' ^ '){ - Fix.calcufix (List[i]); the}Else{ + //System.out.println (Double) (list[i]-' 0 ')); AFix.stack.add ((Double) (list[i]-' 0 ')); the } + } - $Double answer=Stack.pop (); $ System.out.println (answer); - -}
Infix---->postfix
Algorithm:
1. The component direct output is encountered.
2. The operator is encountered, comparing the precedence of the current operator and the top of the stack operator, and the current <= stack is output until it is not <=. Otherwise press stack
3. Given the output, the # operator should be added at the end. The minimum priority so that the expression can end.
4. For (pressed into the stack, encountered) the elements in the stack output, until you encounter (.
infix, suffix expression