-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPost.java
51 lines (43 loc) · 1.38 KB
/
Post.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package Stack;
public class Post {
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 the scanned character is an operand
// (number here), push it to the stack.
if (Character.isDigit(c))
stack.push(c - '0');
// 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();
}
public static void main(String[] args) {
String exp = "231*+9-";
// Function call
System.out.println("postfix evaluation: "
+ evaluatePostfix(exp));
}
}