forked from the-moonLight0/Hactober-fest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infixToPrefix.java
71 lines (64 loc) · 2.03 KB
/
infixToPrefix.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
// Java program to convert infix to prefix.
import java.util.Stack;
public class InfixToPreFix {
static int precedence(char c){
switch (c){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static StringBuilder infixToPreFix(String expression){
StringBuilder result = new StringBuilder();
StringBuilder input = new StringBuilder(expression);
input.reverse();
Stack<Character> stack = new Stack<Character>();
char [] charsExp = new String(input).toCharArray();
for (int i = 0; i < charsExp.length; i++) {
if (charsExp[i] == '(') {
charsExp[i] = ')';
i++;
}
else if (charsExp[i] == ')') {
charsExp[i] = '(';
i++;
}
}
for (int i = 0; i <charsExp.length ; i++) {
char c = charsExp[i];
//check if char is operator or operand
if(precedence(c)>0){
while(stack.isEmpty()==false && precedence(stack.peek())>=precedence(c)){
result.append(stack.pop());
}
stack.push(c);
}else if(c==')'){
char x = stack.pop();
while(x!='('){
result.append(x);
x = stack.pop();
}
}else if(c=='('){
stack.push(c);
}else{
//character is neither operator nor "("
result.append(c);
}
}
for (int i = 0; i <=stack.size() ; i++) {
result.append(stack.pop());
}
return result.reverse();
}
public static void main(String[] args) {
String exp = "A+B*(C^D-E)";
System.out.println("Infix Expression: " + exp);
System.out.println("Prefix Expression: " + infixToPreFix(exp));
}
}