-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInfixPostfix.java
More file actions
74 lines (58 loc) · 1.5 KB
/
InfixPostfix.java
File metadata and controls
74 lines (58 loc) · 1.5 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
package Solutions;
import java.util.Stack;
interface Pattern {
public String conversion(String exp);
}
public class InfixPostfix {
public static void main(String[] args) {
String infix = "a+b*c";
InfixToPostfixPattern ip = new InfixToPostfixPattern();
String postfix = ip.conversion(infix);
System.out.println("Infix: " + infix);
System.out.println("Postfix: " + postfix);
}
}
class InfixToPostfixPattern implements Pattern {
@Override
public String conversion(String exp) {
int priority = 0;// for the priority of operators.
String postfix = "";
Stack<Character> s1 = new Stack<Character>();
for (int i = 0; i < exp.length(); i++) {
char ch = exp.charAt(i);
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%') {
// check the precedence
if (s1.size() <= 0)
s1.push(ch);
else {
Character chTop = (Character) s1.peek();
if (chTop == '*' || chTop == '/')
priority = 1;
else
priority = 0;
if (priority == 1) {
if (ch == '*' || ch == '/' || ch == '%') {
postfix += s1.pop();
i--;
} else { // Same
postfix += s1.pop();
i--;
}
} else {
if (ch == '+' || ch == '-') {
postfix += s1.pop();
s1.push(ch);
} else
s1.push(ch);
}
}
} else {
postfix += ch;
}
}
int len = s1.size();
for (int j = 0; j < len; j++)
postfix += s1.pop();
return postfix;
}
}