import java.util.Stack;
class EvaluationPostfixExpression {
static int evaluatePostfix(String postfix) {
// stack to store operand
Stack stack = new Stack<>();
int ex1, ex2, result;
int i = 0;
while(i < postfix.length()) {
char ch = postfix.charAt(i);
if(isOperand(ch)) {
// if it's operand then add into stack
stack.push(Character.getNumericValue(ch));
} else {
// pop 2 values from stack and apply operator and
//store result back to stack
ex2 = stack.pop();
ex1 = stack.pop();
result = 0; // default value
switch(ch) {
case '+':
result = ex1 + ex2;
break;
case '-':
result = ex1 - ex2;
break;
case '*':
result = ex1 * ex2;
break;
case '/':
result = ex1 / ex2;
break;
}
stack.push(result);
}
i++;
}
// return the stack top
return stack.pop();
}
private static boolean isOperand(char ch) {
switch(ch){
case '+':
case '-':
case '*':
case '/':
case '^':
case '(':
case ')':
return false;
}
return true;
}
public static void main (String[] args) {
String postfix = "234*+82/-";
System.out.println("Postfix : " + postfix + ", Result : " + evaluatePostfix(postfix));
}
}
Output
Postfix : 234*+82/-, Result : 10
Comments
Post a Comment