(Solved) : Java Using Stack Evaluate Expression Often Deal Arithmetic Expressions Written Called Infi Q37182539 . . .
In java
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 number: push itonto the value stack.
1.2.2 A variable: get itsvalue, and push onto the value stack.
1.2.3 A left parenthesis:push it onto the operator stack.You can also
choose to push the left parenthesis into the operand stack.
1.2.4 A rightparenthesis:
1 While thething on top of the operator stack is not a
left parenthesis,
1 Pop the operator from the operator stack.
2 Pop the value stack twice, getting two operands.
3 Apply the operator to the operands, in the correct order.
4 Push the result onto the value stack.
2 Pop the leftparenthesis from the operator stack, and discard it.
1.2.5 An operator (call itthisOp):
1 While theoperator stack is not empty, and the top thing on the
operator stack has the same or greater precedence as thisOp,
1Pop the operator from the operator stack.
2Pop the value stack twice, getting two operands.
3Apply the operator to the operands, in the correct order.
4Push the result onto the value stack.
2 Push thisOponto the operator stack.
- While the operator stack is not empty,
1 Pop the operator from the operatorstack.
2 Pop the value stack twice, getting twooperands.
3 Apply the operator to the operands, in thecorrect order.
4 Push the result onto the value stack.
- At this point the operator stack should be empty, and thevalue
stack should have only one value in it, which isthe final result.
Pay attention to negative operator, it has only one operandafter the negative operator.
PreviousNext
Expert Answer
Answer to In java Using a Stack to Evaluate an Expression We often deal with arithmetic expressions written in what is called infi…
OR