forked from MLSA-MUET-SZAB-Club-Khairpur-Mir-s/Learn-to-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
A.java
58 lines (56 loc) · 1.91 KB
/
A.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
51
52
53
54
55
56
57
58
package DSA;
import java.util.Stack;
public class A {
public String infixToPrefix(String s) {
DSA1 o = new DSA1();
String prefix = "";
Stack<Character> st = new Stack<Character>();
char ch[] = s.toCharArray();
for (char c : ch) {
if (c != '+' && c != '-' && c != '*' && c != '/' && c != '(' && c != ')') {
prefix = c+prefix ;
} else if (c == '(') {
st.push(c);
} else if (c == ')') {
while (!st.isEmpty()) {
char t = st.pop();
if (t != '(') {
prefix = t+prefix ;
} else {
break;
//it is a break statement
}
}
// it is a if-else statement
} 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 (c == '+' || c == '-' || c == '*' || c == '/') {
if (o.getPriority(t) < o.getPriority(c)){
st.push(t);
break;
}
else{
prefix = t+prefix;
}
}
}
st.push(c);
}
}
}
while (!st.isEmpty()){
prefix = st.pop()+prefix;
}
return (prefix);
}
}
// bye bye programming