Basic use and application of stack stack in Java (II.)--using stacks to calculate the legal arithmetic expression

Source: Internet
Author: User
Tags arithmetic

Calculating a valid arithmetic expression using stack stack

Qualified Arithmetic expression evaluation problem: a valid arithmetic expression containing "+", "-", "*", "/", positive integers, and parentheses.

Arithmetic expressions converted to suffix expressions

In programming languages, operators are called infix expressions in the middle of two operands, that is, our usual expression methods, such as 1+2*3.

In infix expression to consider the priority of the operation, first multiplication, after the addition and subtraction, from left to right, and parentheses in the first operation.

The precedence of operators has been taken into account in postfix expressions, and there are no parentheses, only operands and operators.

For example, the above example 1+2*3, infix expression calculation, according to priority, first calculate 2*3=6, and then calculate 1+6=7

Convert to suffix expression 1+2*3 = 123*+,

Scan from left to right the first operator is *, first executes 2*3, the second operator is +, executes 1+6.

Infix expression-to-suffix expression procedure

① Initialize exp character array, resultexp character array (variable), operator stack

Exp character array: stored, valid arithmetic expression

Resultexp character Array (variable): holds suffix expression

Operator Stack: store operator and "=" as the stack-bottom element

② read the character CH from exp, if the number of subsequent operations is stored sequentially into resultexp, and ends with the # flag value

③ If CH is an operator, compare it to the operator at the top of the operator stack to compare precedence

CH priority is greater than top of stack operator precedence, then ch in stack

CH Precedence is less than the top of the stack operator, then the stack operator is retired until the CH operator is greater than the top of the stack operator, and CH is then pushed back into the stack.

The CH priority is equal to the top of the stack operator priority, in special cases, only the parentheses satisfy the case, i.e. ")" with the priority equal to "(" the precedence, which will (fallback).

④EXP scan complete, at this time the operator stack is not empty, then "=" all the operators are retired and put into the Resultexp

An example of a complex point

(12-3)/(4+2)

The algorithm is as follows:

 PackageCom.xumz.stack;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJava.util.Stack;/*** infix expression-to-suffix expression * *@authorXumz 2017/10/18*/ Public classExpressionchange {//the priority of holding the left operatorMap<character, integer> leftoperator =NewHashmap<character, integer>() {{put (' = ', 0); Put (' (', 1); Put (' + ', 3); Put ('-', 3); Put (' * ', 5); Put ('/', 5); Put (') ', 6);    }    }; //Precedence of the right operator for storageMap<character, integer> rightoperator =NewHashmap<character, integer>() {{put (' = ', 0); Put (' (', 6); Put (' + ', 2); Put ('-', 2); Put (' * ', 4); Put ('/', 4); Put (') ', 1);    }    }; /*** infix ext. suffix * *@paramSTR *@return     */     Publicstring trans (string str) {//convert to char[]        Char[] Exp =Str.tochararray (); //Storing conversion resultsList<character> Resultexp =NewArraylist<character>(); //store operator, initial base = ' = 'Stack<character> operator =NewStack<character>(); Operator.push (=); //Scan Exp Expression        inti = 0;  while(I! =exp.length) {//Number Situation            if(!Isoperator (Exp[i])) {                 while(I! = exp.length &&!)Isoperator (Exp[i]))                    {Resultexp.add (exp[i]); I++; } resultexp.add (‘#‘); }            //operator Condition            Else {                Switch(Compareoperatornice (Operator.peek (), Exp[i])) { Case-1: Operator.push (Exp[i]); I++;//continue to the next character                     Break;  Case0: Operator.pop (); I++;//continue to the next character                     Break;  Case1: Resultexp.add (Operator.peek ());                    Operator.pop ();  Break; }            }        }         while(! (Operator.peek () = = ' = ') {Resultexp.add (Operator.peek ());        Operator.pop (); }                //Convert to String return        returnresultexp.tostring (); }    BooleanIsoperator (Charch) {        if(Leftoperator.containskey (ch)) {return true; }        return false; }    /*** Compare left and right operator precedence, return status result * *@paramLeftoperator *@paramRightoperator *@return     */    intCompareoperatornice (CharLeftCharRight ) {        if(Leftoperator.get (left) = =Rightoperator.get (right)) {            return0; }        if(Leftoperator.get (left) <Rightoperator.get (right)) {            return-1; }        return1; }}
View Code

Basic use and application of stack stack in Java (II.)--using stacks to calculate the legal arithmetic expression

Related Article

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.