In the chapter, we examined one strategy to evaluate an infix expression—first convert the infix expression to a postfix expression, then evaluate the resulting postfix expression. An alternative strategy would be to convert the infix expression to prefix, and then evaluate the resulting prefix expression.
The following pseudocode algorithm for converting an infix expression to prefix is similar to, but not quite the same as, the infix to postfix conversion algorithm:
Initialize the string temp to the null string Reverse the characters in the infix expression
for(each character ch in the reversed infix expression) {
switch(ch) {
case ch is an operand:
Append ch to the end of temp expression
case ch is ') ' :
Push ch on the stack
case ch is '(':
Pop stack and append item to output expression until the
matching ') ' is popped off the stack
case ch is an operator:
Pop operators off stack and append to temp expression as
appropriate (similar to postfix conversion)
Push ch on the stack
} //end switch
} //end for
// append remaining stack contents to output expression
while (stack is not empty) {
Pop stack and append to temp expression
}// end while
Reverse temp expression to produce prefix expression
Also note that evaluating a prefix expression is almost the same as evaluating a postfix expression, with one small change—with prefix expressions, you start at the end of the expression. For example:
Postfix : 3 5 +
You start at the beginning of the expression, moving forward through the expression, pushing operands, and popping the operands when tire operators appear, then pushing the result.
Prefix: +35
You start at the end of the expression, moving backward through the expression, pushing operands, and popping the operands when the operators appeal-, dien pushing the result.
Design and implement a class (as shown next) for an infix calculator based on prefix expressions. Use the algorithms given above to convert the infix expression to prefix form and to evaluate the resulting prefix expression. Note diat if the methodsevaluate andgetPrefix are called before theconvertPrefix method, then the exceptionHlegalStateException should be thrown by these methods.
class Calculator {
public Calculator(String exp) // initializes infix expression
public String toString()// returns infix expression
private boolean convertPrefix() // creates prefix expression
// returns true if successful
// The following methods should throw IllegalStateException if // they are called before convertPrefix
// returns the resulting prefix expression
public String getPrefix() throws IllegalStateException
// evaluates the expression
public int evaluate() throws IllegalStateException } //end Calculator
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.