-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPrefix.java
More file actions
64 lines (55 loc) · 1.94 KB
/
Copy pathInfixToPrefix.java
File metadata and controls
64 lines (55 loc) · 1.94 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
import java.util.*;
public class InfixToPrefix {
public static int precedence(char ch){
switch(ch){
case '+' : return 1;
case '-' : return 1;
case '*' : return 2;
case '/' : return 2;
case '^' : return 3;
}
return 0;
}
public static String infixToPrefix(String str) {
Stack<Character> st = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
char ch = str.charAt(i);
if (Character.isLetterOrDigit(ch)) {
sb.append(ch);
} else if (ch == '(') {
while (!st.isEmpty() && st.peek() != ')') {
sb.append(st.peek());
st.pop();
}
st.pop();
} else if (ch == ')') {
st.push(ch);
} else {
if (st.isEmpty()) {
st.push(ch);
} else if (!st.isEmpty() && precedence(ch) >= precedence(st.peek())) {
st.push(ch);
} else {
// if incoming operator precedence is less than st.top. precedence, then keep popping until lower precedence is got
while (!st.isEmpty() && precedence(ch) < precedence(st.peek())) {
sb.append(st.peek());
st.pop();
}
st.push(ch); // Push the incoming operator into the stack
}
}
}
while (!st.isEmpty()) {
sb.append(st.pop());
}
return sb.reverse().toString();
}
public static void main(String args[]){
String str = "x+y*z/w+u";
String Expected_result = "++x/*yzwu";
String output = infixToPrefix(str);
System.out.println(output);
System.out.println(Expected_result);
}
}