-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathReversePolishNotation.java
50 lines (45 loc) · 1.79 KB
/
ReversePolishNotation.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
package java1.algorithms.stack.reversePolishNotation;
import java.util.Stack;
public class ReversePolishNotation {
private static int reversePolishNotation(String[] tokens){
Stack<Integer> myStack = new Stack<>();
for(String token: tokens){
switch (token) {
case "+": {
int secondPrev = Integer.valueOf(myStack.pop());
int firstPrev = Integer.valueOf(myStack.pop());
myStack.push(firstPrev+secondPrev);
break;
}
case "-": {
int secondPrev = Integer.valueOf(myStack.pop());
int firstPrev = Integer.valueOf(myStack.pop());
myStack.push(firstPrev-secondPrev);
break;
}
case "*": {
int secondPrev = Integer.valueOf(myStack.pop());
int firstPrev = Integer.valueOf(myStack.pop());
myStack.push(firstPrev*secondPrev);
break;
}
case "/": {
int secondPrev = Integer.valueOf(myStack.pop());
int firstPrev = Integer.valueOf(myStack.pop());
myStack.push(firstPrev/secondPrev);
break;
}
default:
myStack.push(Integer.parseInt(token));
break;
}
}
return myStack.pop();
}
public static void main(String[] args) {
String[] tokens1 = {"1","3","+","4","*"};
String[] tokens2 = {"5","4","3","2","+","-10","*","/","*","10","+","4","+"};
System.out.println(reversePolishNotation(tokens1));
System.out.println(reversePolishNotation(tokens2));
}
}