Skip to content

Instantly share code, notes, and snippets.

@irfanm96
Created December 20, 2019 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irfanm96/6995e407b86c2a6520986c5a70319f40 to your computer and use it in GitHub Desktop.
Save irfanm96/6995e407b86c2a6520986c5a70319f40 to your computer and use it in GitHub Desktop.
Java Implementation to evaluate a postfix expression using a stack
import java.util.Stack;
public class Main {
public static void main(String[] args) {
// the driver code
String expression1 = "22*3+";
//should print answer as 7
evaluatePostfix(expression1);
String expression2 = "32*2+";
//should print answer as 8
evaluatePostfix(expression2);
String expression3 = "3*2+";
//should print Not a valid expression
evaluatePostfix(expression3);
}
//simple function to evaluate when given operands and the operator
//can be extended to more operators
static int evaluate(int operand1, int operand2, char operator) {
switch (operator) {
case '+':
System.out.println(operand1 + " + " + operand2);
return operand1 + operand2;
case '-':
System.out.println(operand1 + " - " + operand2);
return operand1 - operand2;
case '/':
System.out.println(operand1 + " / " + operand2);
return operand1 / operand2;
case '*':
System.out.println(operand1 + " * " + operand2);
return operand1 * operand2;
default:
return 0;
}
}
static void evaluatePostfix(String expression) {
System.out.println("Evaluating expression " + expression);
Stack<Character> stack = new Stack<Character>();
char[] array = expression.toCharArray();
int i = 0;
while (i < array.length) {
//if its a digit put it in the stack
if (Character.isDigit(array[i])) {
stack.push(array[i]);
} else {
//always stack has to be of size of 2 , if not the expression is not valid
if (stack.size() != 2) {
System.out.println("postfix expression is not valid");
return;
}
//get the operands by popping the stack
int operand1 = Integer.parseInt(String.valueOf(stack.pop()));
int operand2 = Integer.parseInt(String.valueOf(stack.pop()));
//evaluate the operands using the operator
int result = evaluate(operand1, operand2, array[i]);
//push the result back to the stack
stack.push(Character.forDigit(result, 10));
}
i++;
}
//print the result
System.out.println("result is " + stack.pop() + '\n');
}
}
@yossefsabry
Copy link

another way for the code but work for only one digite

// Java program to evaluate value of a postfix
// expression having multiple digit operands
import java.util.Stack;
 
class Test1
{
    // Method to evaluate value of a postfix expression
    static int evaluatePostfix(String exp)
    {
        //create a stack
        Stack<Integer> stack = new Stack<>();
         
        // Scan all characters one by one
        for(int i = 0; i < exp.length(); i++)
        {
            char c = exp.charAt(i);
             
            if(c == ' ')
            continue;
             
            // If the scanned character is an operand
            // (number here),extract the number
            // Push it to the stack.
            else if(Character.isDigit(c))
            {
                int n = 0;
                 
                //extract the characters and store it in num
                while(Character.isDigit(c))
                {
                    n = n*10 + (int)(c-'0');
                    i++;
                    c = exp.charAt(i);
                }
                
 
                //push the number in stack
                stack.push(n);L
            }
             
            // If the scanned character is an operator, pop two
            // elements from stack apply the operator
            else
            {
                int val1 = stack.pop();
                int val2 = stack.pop();
                 
                switch(c)
                {
                    case '+':
                    stack.push(val2+val1);
                    break;
                     
                    case '-':
                    stack.push(val2- val1);
                    break;
                     
                    case '/':
                    stack.push(val2/val1);
                    break;
                     
                    case '*':
                    stack.push(val2*val1);
                    break;
            }
            }
        }
        return stack.pop();
    }
     
    // Driver program to test above functions
    public static void main(String[] args)
    {
        String exp = "100 200 + 2 / 5 * 7 +";
        System.out.println(evaluatePostfix(exp));
    }
}

 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment