-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathinfixtopostfix.java
46 lines (42 loc) · 1.25 KB
/
infixtopostfix.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
package com.company.Stacks;
public class InfixToPostfix {
public static int precedence(String op){
if (op == null){
return -1;
}
if (op.equals("*") || op.equals("/")) {
return 2;
}
if (op.equals("+") || op.equals("-")) {
return 1;
}
return -1;
}
public static StringBuilder infixToPostfix(String inf, CharStack st){
StringBuilder post = new StringBuilder();
int i = 0;
while (i < inf.length()) {
if (inf.charAt(i) == '*' || inf.charAt(i) == '/' || inf.charAt(i) == '+' || inf.charAt(i) == '-'){
if (precedence(inf.substring(i, i + 1)) > precedence(st.stackTop())) {
st.push(inf.substring(i, i + 1));
i++;
}
else{
post.append(st.pop());
}
}
else {
post.append(inf.charAt(i));
i++;
}
}
while (!st.isEmpty()){
post.append(st.pop());
}
return post;
}
public static void main(String[] args) {
CharStack s = new CharStack(10);
System.out.println(infixToPostfix("x-y/z-k*d", s));
}
}