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);
                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) {
                    num = new StringBuffer("");

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

            //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 +";


Leave a Reply


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