-
Notifications
You must be signed in to change notification settings - Fork 17
/
InfixToPostfix.java
69 lines (67 loc) · 2.14 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
package SummerTrainingGFG.Stack;
import java.util.Stack;
/**
* @author Vishal Singh
*/
public class InfixToPostfix {
static int precedence(char a){
switch (a){
case '^':
return 5;
case '/':
case '*':
return 4;
case '+':
case '-':
return 3;
}
return -1;
}
static String infixToPostfix(String exp) {
Stack<Character> stack = new Stack<>();
stack.push('(');
exp = exp+")";
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < exp.length(); i++) {
char currChar = exp.charAt(i);
// System.out.println(stack);
if (("^*/+-()").indexOf(currChar) == -1) {
sb.append(exp.charAt(i));
// System.out.println(sb);
}else {
if (stack.isEmpty()){
stack.push(currChar);
}else{
if (currChar == ')'){
while (stack.peek() != '('){
sb.append(stack.pop());
//System.out.println(sb);
}
stack.pop();
}else {
if (currChar == '('){
stack.push('(');
}
else {
while (true){
if (precedence(currChar) <= precedence(stack.peek())){
sb.append(stack.pop());
//System.out.println(sb);
}else {
stack.push(currChar);
break;
}
}
}
}
}
}
}
//System.out.println(stack);
return sb.toString();
}
public static void main(String[] args) {
String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(exp));
}
}