-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP12.java
More file actions
58 lines (46 loc) · 1.64 KB
/
P12.java
File metadata and controls
58 lines (46 loc) · 1.64 KB
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
52
53
54
55
56
57
58
package stack_and_queue;
// Problem Title => Java program to evaluate value of a postfix expression
import java.util.*;
import java.util.Stack;
public class P12 {
// 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 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();
}
// Driver program to test above functions
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String exp = sc.nextLine();
sc.close();
// String exp="231*+9-";
System.out.println("postfix evaluation: "+evaluatePostfix(exp));
}
}