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