Stack: Evaluate a postfix expression

Question: Evaluate a postfix expression

package additional_problems.stack;

/**
 * Note that every number must have spaces between them
 * 1. Start from the first element of the post fix expression
 * 2. If operand encountered, then push onto stack
 * 3. If operator encountered, pop the top two elements and evaluate operator2- operator1
 * 4. Push result onto stack
 * 5. Once entire expression is traversed, return top of stack
 * Created by aarushi on 7/7/21.
 */
public class P06EvaluationOfPostfixMoreThanOneDigit {

    public static double evaluate(char operator, double operand2, double operand1){
        switch (operator){
            case '+':
                return operand1+operand2;
            case '-':
                return operand1-operand2;
            case '*':
                return operand1*operand2;
            case '/':
                return operand1/operand2;
            case '%':
                return operand1%operand2;
            case '^':
                return Math.pow(operand1, operand2);
            default:
                return 0;
        }
    }


    public static double evaluatePostfix(String postfixExpression){
        DoubleStack stack = new DoubleStack(postfixExpression.length());
        StringBuffer num= new StringBuffer();

        //1. Start from the first element of the post fix expression
        for(int i=0; i<postfixExpression.length(); i++){
            char c= postfixExpression.charAt(i);

            // if space is encountered then the number is complete
            if(c==' '){
                if(num.length()>0) {
                    stack.push(Double.parseDouble(num.toString()));
                    num = new StringBuffer("");
                }
            }

            //2. If operand occurred then append to num
            else if (c >= '0' && c <= '9') {
                num.append(c);
            }

            //3. If operator occurred then pop top two elements from stack and evaluate expression
            //4. Push result onto stack
            else if (c=='+' || c=='-' || c=='*' || c=='/' || c=='%' | c=='^'){
                stack.push(evaluate(c, stack.pop(), stack.pop()));
            }
        }

        //5. Once entire expression is traversed, return top of stack
        return stack.pop();
    }

    public static void main (String[]args){
        String postfixExpression="100 200 + 2 / 5 * 7 +";
        System.out.println(evaluatePostfix(postfixExpression));
    }


}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close