-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfixToPostfix.java
90 lines (67 loc) · 2.03 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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.Stack;
public class infixToPostfix {
public static void main(String[] args) {
String s = "A+B*C+D";
System.out.println(infixToPostfix(s));
}
static String infixToPostfix(String s){
Stack<Character> st = new Stack<>();
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;
}
static int getPriority(char c){
if(c == '+' || c == '-'){
return 1;
}
else{
return 2;
}
}
}