forked from Abraarkhan/Java_Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix2infix.java
55 lines (42 loc) · 1.08 KB
/
postfix2infix.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
import java.util.*;
class PostfixToInfix
{
static boolean isOperand(char ch)
{
// we check for uppercase and lowercase alphabets.
if(ch >= 'a' && ch <= 'z')
return true;
else if(ch >= 'A' && ch <= 'Z')
return true;
return false; // if not an Operand return false;
}
// converts postfix to infix and returns the expression
static String convertToInfix(String postfix)
{
Stack<String> inFix = new Stack<>();
for (int i = 0; i < postfix.length(); i++)
{
char ch = postfix.charAt(i);
if (isOperand(ch))
{
// Push operands to stack.
inFix.push(ch + "");
}
// Step 2: Evaluate part of the expression and push it again to stack.
else
{
String op1 = inFix.pop();
String op2 = inFix.pop();
inFix.push("(" + op2 + ch + op1 + ")");
}
}
return inFix.pop();
}
public static void main(String args[])
{
String postfix = "ABC-*D/";
System.out.println("The Postfix Expression is: "+ postfix);
String result = convertToInfix(postfix);
System.out.println("The Infix Expression is : "+result);
}
}