-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathPrefix_to_inflix.java
63 lines (54 loc) · 1.27 KB
/
Prefix_to_inflix.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
filter_none
edit
play_arrow
brightness_4
// Java program to convert prefix to Infix
import java.util.Stack;
class GFG{
// Function to check if character
// is operator or not
static boolean isOperator(char x)
{
switch(x)
{
case '+':
case '-':
case '*':
case '/':
return true;
}
return false;
}
// Convert prefix to Infix expression
public static String convert(String str)
{
Stack<String> stack = new Stack<>();
// Length of expression
int l = str.length();
// Reading from right to left
for(int i = l - 1; i >= 0; i--)
{
char c = str.charAt(i);
if (isOperator(c))
{
String op1 = stack.pop();
String op2 = stack.pop();
// Concat the operands and operator
String temp = "(" + op1 + c + op2 + ")";
stack.push(temp);
}
else
{
// To make character to string
stack.push(c + "");
}
}
return stack.pop();
}
// Driver code
public static void main(String[] args)
{
String exp = "*-A/BC-/AKL";
System.out.println("Infix : " + convert(exp));
}
}