Answered You can hire a professional tutor to get the answer.

QUESTION

private String convertToPostfix(String infix) { /* Task:

 private String convertToPostfix(String infix)

  {

     /*

       Task: Convert an infix expression to a postfix expression

 Use Stack<Character> S to hold operator characters

       Valid characters are '(',')','+','-','*','/', predefined variable names

 Use a StringBuffer PE to hold postfix expression

 Need to consider : ‘(‘ & ‘)’, precedence of operators and left to right association

 Step 1. Process each character ch in infix expression from left to right

 switch(ch)

 {

  case operand : append to PE; break;

  case ‘(‘ : S.push(ch); break;

  case ‘)’ : repeat // loop until “(“

                   {

     symbol = S.pop()

     if symbol != ‘(‘ then append to PE

     else exit loop

     }

            break;

  case operator : get TopSymbol from S if S is not empty

     while (!S.isEmpty()) and (TopSymbol != ‘(‘) and

     (precedence(ch) <= precedence(TopSymbol))

     {

     symbol = S.pop()

     append symbol to PE

     get TopSymbol from S if S is not empty

     }

     S.push(ch)

     break;

 } // end switch

 Step 2. After scanning the whole infix expression. Append remaining operators in S into PE

 while (Stack != empty)

 {

  symbol = S.pop();

  append symbol to PE

 }

 Return PE.toString() // convert StringBuffer to String

 Example : (a*b+c) â€" (d-e*f) == ab*c+def*-- 

 Char  Stack  PE 

 (  (  

 a  (  a

 *  (*  a

 b  (*  ab

 +  (+  ab*

 c  (+  ab*c

 )    ab*c+

 -  -  ab*c+

 (  -(  ab*c+

 d  -(  ab*c+d

 -  -(-  ab*c+d

 e  -(-  ab*c+de

 *  -(-*  ab*c+de

 f  -(-*  ab*c+def

 )  -  ab*c+def*-

     ab*c+def*--  

 */

 return null; //change it

  } // end convertToPostfix

  /** Evaluates a postfix expression.

      Must only use variable names as defined in variable table

      @param postfix : A valid postfix expression.

      @return The double result of the postfix expression. */

  private double evaluatePostfix(String postfix)

  {

     /*

  Task: Evaluate a postfix expression

 Use a Stack<Double> S to hold operands

 Process each character ch in postfix expression from left to right

  if a character is an operand : push into S

  if a character is an operator :

   pop two operands from S

   evaluate the result (need to consider +,-,*,/)

   push the result back to S

 Final result is in S

 Hint: Use getVariableValue(X) to get value of variable X

      Use checkValidVariable(X) to check if X is a variable

      Use checkValidOperator(X) to check if X is an operator

 Example : Let A=2, B=3, C=4, D=5.

   Evaluate postfix expr “ABC+*D-“

   234+*5- = 2 * (3+4) â€" 5 = 9

   Char  Stack   

   2  2    

   3  2,3    

   4  2,3,4   

   +  2,7 // 3 + 4  

          *  14 // 2 * 7  

   5  14,5    

     -  9 // 14 - 5

   Result = 9

Show more
LEARN MORE EFFECTIVELY AND GET BETTER GRADES!
Ask a Question