Using a Stack to Evaluate an Expression
We often deal with arithmetic expressions written in what iscalled infix notation:
Operand1 opOperand2
We have rules to indicate which operations take precedence overothers, and we often use parentheses to override those rules.
Example: Suppose we have this infix expression Q:
5 * ( 6 + 2 ) -12 / 4
We can use two stacks to evaluate the expression: a stack foroperands, a stack for operators (and parenthesis). We can split thestring into array of tokens.
- While there are still tokens to be read in,
1.1 Get the next token.
1.2 If the token is:
1.2.1 A
OR
OR