-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathinfixTopostfix.java
More file actions
77 lines (67 loc) · 1.74 KB
/
infixTopostfix.java
File metadata and controls
77 lines (67 loc) · 1.74 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.Stack;
class infixToPostfixx {
public String infixToPostfix1(String s) {
Stack<Character> st = new Stack<Character>();
String postfix = "";
char ch[] = s.toCharArray();
for(char c: ch)
{
if(c != '+' && c != '-' && c != '*' && c != '/' && c != '(' && c != ')') {
postfix = postfix + c;
} else if (c == '(') {
st.push(c);
} else if (c == ')') {
while(!st.isEmpty()) {
char t = st.pop();
if(t != '(') {
postfix = postfix + t;
} else {
break;
}
}
} else if(c == '+' ||c == '-' ||c == '*' ||c == '/') {
if(st.isEmpty()) {
st.push(c);
} else {
while(!st.isEmpty()) {
char t = st.pop();
if(t == '(') {
st.push(t);
break;
} else if(t == '+' || t == '-' || t == '*' || t == '/') {
if(getPriority(t) < getPriority(c)) {
st.push(t);
break;
} else {
postfix = postfix + t;
}
}
}
st.push(c);
}
}
}
while(!st.isEmpty()) {
postfix = postfix + st.pop();
}
return postfix;
}
public int getPriority(char c) {
if(c == '+' || c == '-') {
return 1;
} else {
return 2;
}
}
}
public class infixTopostfix {
public static void main(String[] args) {
infixToPostfixx a = new infixToPostfixx();
String s1 = a.infixToPostfix1("A+(B*C)");
System.out.println(s1);
String s2 = a.infixToPostfix1("2+3*4");
System.out.println(s2);
String s3 = a.infixToPostfix1("3*(4+5)-6/(1+2)");
System.out.println(s3);
}
}