JS infix expression converted to postfix expression

Source: Internet
Author: User
Tags stack pop

Algorithm called逆波兰表达式
Inverse Polish expression, its syntax stipulates that expressions must be given in inverse Polish expressions. The inverse Polish expression is also called the suffix expression. This knowledge point is presented in the two courses of data structure and compiling principle, here are some examples:
Normal expression Inverse Polish expression
A+b---> a,b,+
A + (B-C)---> a,b,c,-, +
A + (B-C)d---> A,d,b,c,-,,+
A=1+3---> a=1,3 +
What does http= (smtp+http+telnet)/1024 write?
http=smtp,http,telnet,+,+,1024,/
The inverse Polish expression is a very useful expression that transforms a complex expression into an expression that can rely on a simple operation to get the result of the calculation. For example (A+B)(c+d) converted to ab+cd+
Its advantage is that only two simple operations, into the stack and out of the stack can be done for any ordinary expression operation. The operation is as follows:
If the current character is a variable or a number, then the stack, if it is an operator, then the top two elements of the stack pop up as a corresponding operation, the result is then into the stack, and finally when the expression scan, the stack is the result.
The general algorithm for converting a normal middle-order expression to an inverse Polish expression is:
(1) First constructs an operator stack, which follows the principle that the higher the top priority of the stack is in the stack.
(2) read into a simple arithmetic expression expressed in infix, for convenience, set the right end of the simple arithmetic expression plus the lowest priority special symbol "#".
(3) scan from left to right the arithmetic expression, starting from the first character, if the character is a number, then parse to the end of the number string and output the number directly.
(4) If it is not a number, the character is an operator, at which time the precedence relationship needs to be compared.
This is done as follows: Compares this character to the precedence of the operator at the top of the operator stack. If the character precedence is higher than the operator at the top of this operator stack, the operator is put into the stack. If not, the top operator is popped out of the stack until the top of the stack operator is lower than the current operator and the character is placed on the stack.
(5) Repeat the above operation (3)-(4) until the complete simple arithmetic expression is scanned, to make sure that all characters are handled correctly, we can convert the simple arithmetic expression of infix notation into a simple arithmetic expression of inverse polish representation.
Here is the programmatic algorithm flow:
1, build the operator stack stackoperator for the storage of operators, pressing into ' \ '.
2, preprocessing expression, positive, minus sign plus 0 (if a plus sign (minus) appears in front of the first or after the opening parenthesis, then the plus sign (minus) is signed).
3, sequential scan expression, if the current character is a number (priority 0 symbol), the direct output of the number, if the current character is an operator or parenthesis (priority is not a 0 symbol), then the 4th is judged.
4, if the current operator is ' (', directly into the stack;
If ') ', stack and sequentially output the operator until it encounters the first ' (', the first encountered ' (' out of the stack but not output;
For other, compare the priority of the top element of the Stackoperator stack with the current element:
If the top element of the stack >= the current element, stack and sequentially output the operator until the top element of the stack < The current element, and then the current element into the stack;
If the top element of the stack < The current element, go directly into the stack.
5, repeat the 3rd until the expression scan is complete.
6, sequentially out of the stack and output operators until the top of the stack element is ' \. '
Each operator and symbol priority:
' + ':-1
') ': 1
' (': 2
' + ', '-': 3
' * ', '/', '% ': 4
' ^ ': 5
Other: 0

/*** calculates the value of the inverse Polish expression */function calculate (Rpolisharray) {var result = 0;    var temparray = new Array (100);    var tempnum =-1;            for (i = 0;i < rpolisharray.length;i++) {if (Rpolisharray[i].match (/\d/)) {tempnum++;        Temparray[tempnum] = Rpolisharray[i]; }else{switch (Rpolisharray[i]) {case ' + ': result = (temparray[tempnum-1] *)                    + (Temparray[tempnum] * 1);                    tempnum--;                    Temparray[tempnum] = result;                Break                    Case '-': result = (temparray[tempnum-1] *)-(Temparray[tempnum] * 1);                    tempnum--;                    Temparray[tempnum] = result;                Break                    Case ' * ': result = (temparray[tempnum-1] *) * (Temparray[tempnum] * 1);                    tempnum--;                    Temparray[tempnum] = result;                Break          Case '/':          result = (Temparray[tempnum-1] (*)/(Temparray[tempnum] * 1);                    tempnum--;                    Temparray[tempnum] = result;            Break        }}} result = Temparray[tempnum];  return result;    }/*** converts a normal arithmetic expression to an inverse Polish expression */function torpolish (input) {var regex =/(\ (|\) |\+|\-|\*|\/) +/;    var array = input.split (regex);    var rpolish = "" var IsI = false;    num = 0;    var symbolarray = new Array (100);    var symbolnum =-1;                for (j = 0;j < input.length;j++) {if (Input.charat (j). Match (/\d/)) {if (IsI = = False) {                Rpolish + = ', ' rpolish + = Array[num];                num++;            IsI = true;                    }} else{if (symbolnum = =-1) {symbolnum++;            Symbolarray[symbolnum] = Input.charat (j); }else{if (Input.charat (j). Match (/\ (/) | |     Symbolarray[symbolnum].match (/\ (/)) {                   symbolnum++;                Symbolarray[symbolnum] = Input.charat (j); }else if (Input.charat (j). Match (/\)/)) {while (!                                             Symbolarray[symbolnum].match (/\ (/)) {rpolish + = ', ';                        Rpolish + = Symbolarray[symbolnum];                    symbolnum--;                } symbolnum--;                        }else if (Compare (Input.charat (j), Symbolarray[symbolnum])) {symbolnum++;                Symbolarray[symbolnum] = Input.charat (j);                         }else if (!compare (Input.charat (j), Symbolarray[symbolnum]) {rpolish + = ', ';                        Rpolish + = Symbolarray[symbolnum];                        symbolnum--; if (symbolnum >= 0) {if (Symbolarray[symbolnum].match (/\ (/)) {S                                ymbolnum++; SymbolaRray[symbolnum] = Input.charat (j);                                }else if (!compare (Input.charat (j), Symbolarray[symbolnum]) {rpolish + = ', ';                                Rpolish + = Symbolarray[symbolnum];                            Symbolarray[symbolnum] = Input.charat (j);                                }else{symbolnum++;                            Symbolarray[symbolnum] = Input.charat (j);                            }}else{symbolnum++;                        Symbolarray[symbolnum] = Input.charat (j);        }}} IsI = false;        }} while (Symbolnum >=0) {rpolish + = ', ';        Rpolish + = Symbolarray[symbolnum];    symbolnum--;    } regex =/,/;    var Rpolisharray = rpolish.split (regex); return Rpolisharray;} function Compare (A, B) {if (A.match (/\*/) | | | A.match (/\//)) &AMP;&AMP; (B.match (/\+/) | |    B.match (/\-/)) {return true;    }else{return false; }}

  

JS infix expression converted to postfix expression

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.