Repository navigation
Expand file tree
/
Copy pathExpressionEvaluation.java
More file actions
47 lines (44 loc) · 1.51 KB
/
Copy pathExpressionEvaluation.java
File metadata and controls
47 lines (44 loc) · 1.51 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
/*Copyright (c) Dec 21, 2014 CareerMonk Publications and others.
* E-Mail : info@careermonk.com
* Creation Date : 2015-01-10 06:15:46
* Last modification : 2006-05-31
by : Narasimha Karumanchi
* Book Title : Data Structures And Algorithms Made In Java
* Warranty : This software is provided "as is" without any
* warranty; without even the implied warranty of
* merchantability or fitness for a particular purpose.
*
*/
package chapter04stacks;
import java.util.Stack;
public class ExpressionEvaluation {
public int expressionEvaluation(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
for(String token : tokens){
if(token.equals("+")){
int op1 = s.pop();
int op2 = s.pop();
int res = op1+op2;
s.push(res);
}else if(token.equals("-")){
int op1 = s.pop();
int op2 = s.pop();
int res = op2-op1;
s.push(res);
}else if(token.equals("*")){
int op1 = s.pop();
int op2 = s.pop();
int res = op1 * op2;
s.push(res);
}else if(token.equals("/")){
int op1 = s.pop();
int op2 = s.pop();
int res = op2 / op1;
s.push(res);
}else{
s.push(Integer.parseInt(token));
}
}
return s.pop();
}
}