Write a full program in JAVA using stack implementation toconvert an infix expression to postfix; your program should evaluate thepostfix expression.
The following display the steps for conversion andevaluation.
Conversionfrom infix to postfix algorithem*
Create an empty stack called
opstack for keeping operators. Create an empty list for output.
Convert the input infix string to a list by using the string method
split.
Scan the token list from left to right.
If the token is an operand, append it to the end of the output list.
If the token is a left parenthesis, push it on the
opstack.
If the token is a right parenthesis, pop the
opstack until the corresponding left parenthesis is removed. Append each operator to the end of the output list.
If the token is an operator, *, /, +, or -, push it on the
opstack. However, first remove any operators already on the
opstack that have higher or equal precedence and append them to the output list.
When the input expression has been completely processed, check the
opstack. Any operators still on the stack can be removed and appended to the end of the output list.
The figure below shows the conversion algorithm working on the expression A * B + C * D. Note that the first * operator is removed upon seeing the + operator. Also, + stays on the stack when the second * occurs, since multiplication has precedence over addition. At the end of the infix expression the stack is popped twice, removing both operators and placing + as the last operator in the postfix expression
https://interactivepython.org/course...s/intopost.png
PostfixEvaluation algorithm*
https://interactivepython.org/course...alpostfix1.png
https://interactivepython.org/course...alpostfix2.png
Assume the postfix expression is a string of tokens delimited by spaces. The operators are *, /, +, and - and the operands are assumed to be single-digit integer values. The output will be an integer result.
Create an empty stack called
operandStack.
Convert the string to a list by using the string method
split.
Scan the token list from left to right.
If the token is an operand, convert it from a string to an integer and push the value onto the
operandStack.
If the token is an operator, *, /, +, or -, it will need two operands. Pop the
operandStack twice. The first pop is the second operand and the second pop is the first operand. Perform the arithmetic operation. Push the result back on the
operandStack.
When the input expression has been completely processed, the result is on the stack. Pop the
operandStack and return the value.
المفضلات