forked from aryangulati/DEV
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfixtoInfix.java
More file actions
54 lines (47 loc) · 1.11 KB
/
Copy pathPostfixtoInfix.java
File metadata and controls
54 lines (47 loc) · 1.11 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
// Java program to find infix for
// a given postfix.
import java.util.*;
class PostfixtoInfix
{
static boolean isOperand(char x)
{
return (x >= 'a' && x <= 'z') ||
(x >= 'A' && x <= 'Z');
}
// Get Infix for a given postfix
// expression
static String getInfix(String exp)
{
Stack<String> s = new Stack<String>();
for (int i = 0; i < exp.length(); i++)
{
// Push operands
if (isOperand(exp.charAt(i)))
{
s.push(exp.charAt(i) + "");
}
// We assume that input is
// a valid postfix and expect
// an operator.
else
{
String op1 = s.peek();
s.pop();
String op2 = s.peek();
s.pop();
s.push("(" + op2 + exp.charAt(i) +
op1 + ")");
}
}
// There must be a single element
// in stack now which is the required
// infix.
return s.peek();
}
// Driver code
public static void main(String args[])
{
String exp = "ab*c+";
System.out.println( getInfix(exp));
}
}