Skip to content

Commit ecf7525

Browse files
authored
Create EvalutatePostFix.java
A Program To Evaluate The PostFix Expression Using Stack Data Structure Using Java
1 parent 943b3c7 commit ecf7525

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

EvalutatePostFix.java

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//Input: tokens = ["2","1","+","3","*"]
2+
//Output: 9
3+
//Explanation: ((2 + 1) * 3) = 9
4+
5+
public int evalRPN(String[] tokens) {
6+
Stack<String> stack = new Stack<>();
7+
for(String s : tokens){
8+
if(Objects.equals(s, "+") || Objects.equals(s, "-") || Objects.equals(s, "/") || Objects.equals(s, "*")){
9+
10+
if(s.equals("+")){
11+
int first = Integer.parseInt(stack.pop());
12+
int second = Integer.parseInt(stack.pop());
13+
int n = second+first;
14+
stack.push(Integer.toString(n));
15+
}
16+
17+
else if(s.equals("-")){
18+
int first = Integer.parseInt(stack.pop());
19+
int second = Integer.parseInt(stack.pop());
20+
int n = second-first;
21+
22+
stack.push(Integer.toString(n));
23+
}
24+
25+
else if(s.equals("*")){
26+
int first = Integer.parseInt(stack.pop());
27+
int second = Integer.parseInt(stack.pop());
28+
int n = second*first;
29+
30+
stack.push(Integer.toString(n));
31+
}
32+
else if(s.equals("/")){
33+
int first = Integer.parseInt(stack.pop());
34+
int second = Integer.parseInt(stack.pop());
35+
int n = second/first;
36+
37+
stack.push(Integer.toString(n));
38+
}
39+
}
40+
else{
41+
stack.push(s);
42+
}
43+
}
44+
return Integer.parseInt(stack.pop());
45+
}

0 commit comments

Comments
 (0)