-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixtopostfix.java
More file actions
48 lines (44 loc) · 1.21 KB
/
infixtopostfix.java
File metadata and controls
48 lines (44 loc) · 1.21 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
#application of stacks
import java.util.*;
public class Postfix
{
static int postfix(String exp)
{
Stack<Integer> stk = new Stack<>();
for(int i=0; i<exp.length(); i++)
{
char c = exp.charAt(i);
if(Character.isDigit(c))
{
stk.push(c-'0'); //this converts the character to integer
}
else
{
int v1 = stk.pop();
int v2 = stk.pop();
switch(c)
{
case '+':
stk.push(v1+v2);
break;
case '-':
stk.push(v2-v1);
break;
case '*':
stk.push(v2*v1);
break;
case '/':
stk.push(v2/v1);
break;
}
}
}
return stk.pop();
}
public static void main(String args[])
{
String exp="10+3*5/16-4";
#changing the above expression
System.out.println("postfix evaluation: "+postfix(exp));
}
}