-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathinfix2postfix.java
103 lines (76 loc) · 2.5 KB
/
infix2postfix.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.*;
public class InfixtoPostfix
{
public static int precedence(char ch)
{
if(ch=='+' || ch=='-')
return 1;
else if(ch=='*' || ch=='/')
return 2; // * and / divide have higher precedence.
return 0;
}
public static String convertToPostfix(String exp)
{
Stack<Character> operators = new Stack<>();
Stack<String> postFix = new Stack<>();
for(int i=0;i<exp.length();i++)
{
char ch=exp.charAt(i); // current character.
if(ch=='(')
operators.push(ch);
else if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
postFix.push(ch+"");
else if(ch==')')
{
while(operators.peek()!= '(')
{
// STEP 5 of Algorithm.
char op = operators.pop();
String first = postFix.pop(); // get the two operands.
String second = postFix.pop();
String new_postFix = second+first+op; // add them in reverse order.
postFix.push(new_postFix); // push the result to postFix stack again.
}
operators.pop(); // pop '(' from stack.
}
// We do the same thing if we get an operator as the current character.
else if(ch=='+' || ch=='-' || ch== '*' || ch== '/')
{
// check precedence of each operator with top of the stack and process them.
while(operators.size()>0 && operators.peek()!='(' && precedence(ch) <= precedence(operators.peek()))
{
char op = operators.pop();
String first = postFix.pop();
String second = postFix.pop();
String new_postFix = second+first+op;
postFix.push(new_postFix);
}
operators.push(ch);
}
}
// If the operator stack still has some elements in it process them too Repeat Step 5.
while(operators.size()>0)
{
char op = operators.pop();
String first = postFix.pop();
String second = postFix.pop();
String new_postFix = second+first+op;
postFix.push(new_postFix);
}
return postFix.pop(); // return resultant Postfix.
}
public static void main(String args[])
{
// We pass Uppercase Infix
String infixExpression = "A*(B-C)/D+E";
System.out.println("The Infix Expression is: "+infixExpression);
String result = convertToPostfix(infixExpression);
System.out.println("The Postfix of the given Infix Expression is: "+result);
System.out.println();
//We also check for Lowercase Infix
infixExpression = "a*(b-c+d)/e";
System.out.println("The Infix Expression is: "+infixExpression);
result = convertToPostfix(infixExpression);
System.out.println("The Postfix of the given Infix Expression is: "+result);
}
}