Simple implementation of inverse Polish expression (RPN) algorithm

Source: Internet
Author: User
Tags arithmetic

Algorithm Analysis:

First, pretreatment

Given any arithmetic string expression (infix expression), Predeal is pre-converted to the corresponding string array, which is intended to separate the operands from the operators.

For example, the infix expression within a given arithmetic:

String infix = "100+8*5-(10/2) *5+10.5";

Array of strings:

{"100", "+", "8", "*", "5", "-", "(", "10", "/", "2", ")", "+", "10.5"}

Second, infix expression to postfix expression

Rules:

ergodic infix expression,

A, if you encounter the direct output of the operand

B, if an operator is encountered, divide the situation:

B1: If it is a *,/or (these three operators, direct pressure stack

B2: If yes), the stack is out until it encounters (position. (the left parenthesis and parentheses do not participate in the concatenation suffix expression).

B3: If it is + or-, play the stack until the stack is empty, then speak the current + or-press stack.

Where Condition B can be summed up:

When the closing parenthesis is encountered and the opening parenthesis is matched, the operator is encountered, and if its precedence is higher than the top of the stack, the stack is continued, otherwise the stack is pushed.

Third, calculate the suffix expression

Rules:

To traverse a suffix expression:

A, encountered the operation of the pressure stack

B, encountered operator will be the top of the stack and the top two elements of the stack to participate in the corresponding operation, and then the results of the operation knot stack.

Java Algorithm implementation:

1  Packageagstring;2 ImportJava.util.*;3 4 5  Public classRPN {6      Public Staticstring[] Predeal (String infix) {7Infix =Infix.trim ();8         intLength =infix.length ();9Arraylist<string> infixofarraylist =NewArraylist<string>();Ten         CharCurrchar; One         intindex = 0; A         FinalString regex = "\\+|-|\\*|\\/|\\ (|\\)"; -          for(inti = 0; i < length; i++) { -Currchar =Infix.charat (i); the             if(String.valueof (Currchar). Matches (regex)) {//operator -                 if(Index <i) { -Infixofarraylist.add (infix.substring (index,i));//Add number -                 } + Infixofarraylist.add (string.valueof (Currchar)); -index = i+1; +             } A         } at Infixofarraylist.add (infix.substring (index,length)); -         returnInfixofarraylist.toarray (Newstring[infixofarraylist.size ()]); -     } -      Public Staticstring[] Getpostfix (String infix) { -string[] Infixofary =Predeal (infix); -         intLength =infixofary.length; inarraydeque<string> stack =NewArraydeque<string>(); -String currstring = ""; to         FinalString regex = "\\+|-|\\*|\\/|\\ (|\\)"; +Arraylist<string> postfixofarraylist =NewArraylist<string>(); -          for(inti = 0; i < length; i++) { theCurrstring =Infixofary[i]; *             if(Currstring.matches (Regex)) {//symbol $                 if(Currstring.matches ("\\*|\\/|\\ (")) {Panax Notoginseng Stack.offerfirst (currstring); -}Else{//),+,- theString top = ""; +                     if(Currstring.equals (")")){ A                          while(!Stack.isempty ()) { thetop =Stack.removefirst (); +                             if(Top.equals ("(")) { -                                  Break; $                             } $ Postfixofarraylist.add (top); -                         } -}Else{//+ ,- the                         if(!Stack.isempty ()) { -top =Stack.peekfirst ();Wuyi                             if(Top.equals ("*") | | top.equals ("/")) { the                                  while(!Stack.isempty ()) { - Postfixofarraylist.add (Stack.removefirst ()); Wu                                 } -                             } About                         } $ Stack.offerfirst (currstring); -                     } -                 } -}Else{// Number A Postfixofarraylist.add (currstring); +             } the         } -          while(!Stack.isempty ()) { $ Postfixofarraylist.add (Stack.removefirst ()); the         } the         returnPostfixofarraylist.toarray (Newstring[postfixofarraylist.size ()]); the     } the      Public Static DoubleComputepostfix (String infix) { -string[] Postfixary =Getpostfix (infix); inarraydeque<double> stack =NewArraydeque<double>(); the         intLength =postfixary.length; theString currstring = ""; About         FinalString regex = "\\+|-|\\*|\\/|\\ (|\\)"; the         DoubleOperandone,operandtwo; the          for(inti = 0; i < length; i++) { theCurrstring =Postfixary[i]; +             if(Currstring.matches (regex)) { -Operandone =Stack.removefirst (); theOperandtwo =Stack.removefirst ();Bayi                 Switch(Currstring.charat (0)) { the                  Case+: theStack.addfirst (Operandtwo +operandone); -                      Break; -                  Case‘-‘: theStack.addfirst (Operandtwo-operandone); the                      Break; the                  Case‘*‘: theStack.addfirst (Operandtwo *operandone); -                      Break; the                  Case‘/‘: theStack.addfirst (Operandtwo/operandone); the                      Break;94                 } the                  the}Else { the Stack.addfirst (double.parsedouble (currstring));98             } About         } -         returnStack.removefirst ();101     }102      Public Static voidMain (string[] args) {103         //TODO auto-generated Method Stub104         Try { theString infix = "100+8*5-(10/2) *5+10.5";106             Doubleresult =Computepostfix (infix);107 System.out.println (Result); 108}Catch(Exception e) {109             //Todo:handle Exception the e.printstacktrace ();111         } the     }113  the}

Simple implementation of inverse Polish expression (RPN) algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.