Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 561a178

Browse files
Update Stack.md
1 parent fdb16b9 commit 561a178

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎DataStructures/Stack.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,49 @@
1+
**Evaluate Post fix expression**
2+
```
3+
public int evalPostFixExp(String expr) {
4+
if(expr.equals(""))
5+
return 0;
6+
Stack<Integer> stack = new Stack<>();
17
8+
for (int i = 0; i < expr.length(); i++) {
9+
char c = expr.charAt(i);
10+
if (Character.isDigit(c))
11+
stack.push(c-'0');
12+
else if(isOp(c)) {
13+
int b = stack.pop();
14+
int a = stack.pop();
15+
stack.push(execOp(c,a,b));
16+
} else
17+
throw new IllegalArgumentException("Invalid input");
18+
}
19+
return stack.pop();
20+
}
21+
22+
private int execOp(char op, int a, int b) {
23+
switch (op) {
24+
case '+':
25+
return (a+b);
26+
case '-':
27+
return (a-b);
28+
case '*':
29+
return (a*b);
30+
case '/':
31+
return (a/b);
32+
case '^':
33+
return (int) Math.pow(a,b);
34+
}
35+
throw new IllegalArgumentException("Invalid Input");
36+
}
37+
38+
private boolean isOp (char c) {
39+
switch (c) {
40+
case '+':
41+
case '-':
42+
case '*':
43+
case '/':
44+
case '^':
45+
return true;
46+
}
47+
return false;
48+
}
49+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /