Two-Stack arithmetic expression

Source: Internet
Author: User

1. Introduction

The calculation of arithmetic expressions is a more common problem, but the idea behind this problem is hidden in the stack.

Here's how to use two stacks to evaluate an expression.

2. Algorithm 2.1 defines:

A) build two stacks:

One is the data stack Datastak, for storing data;

One is the symbol stack operatorstack, which is used for storing operators;

b) Establish a priority table between the operational symbols to compare the priority between the two symbols;

The priority is defined as the result of three operations:> (denoted above),< (denoted below), = (denotes equality);

And for "(" and ")", think that the two are the same priority, do not do any operations;

2.2 Calculation conditions:

A) when (b) c) d) is met, calculations can be made;

b) The current token is an operator (that is, it cannot be a string terminator or an operand);

c) The symbol stack is non-empty (because it needs to be compared with the top element of the stack);

d) Priority of stack top element of symbol stack < current token;

The remaining operand of the last operand stack is the final result of the calculation;

2.3 Priority Symbol Table
Char[,] priority =New Char[6,6] {            //+   -    *   /  (   ){'>','>','<','<','<','>'},//+{'>','>','<','<','<','>'},//-{'>','>','>','>','<','>'},//*{'>','>','>','>','<','>'},///{'<','<','<','<','<','='},//({'<','<','<','<','<','>'}//)};

2.4 Pseudo-code

for each tokenif(token is a number) {Datastack.push (token);}Else{    Switch(token versus operatorstack stack top element for precedence comparison) { Casegreater than: Datastack.push (token);  Break;  Caseless than: operator=Operatorstack.pop (); A=Datastack.pop (); b=Datastack.pop (); C=a operator B;                Datastack.push (c);  Break;  Caseequals: Datastack.pop ();  Break; }}

Two-Stack 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.