-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfixToPostfixDemo.java
96 lines (63 loc) · 2.06 KB
/
InfixToPostfixDemo.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
import java.util.Stack;
class InfixToPostfixDemo{
static String result="";
static Stack<Character> stack = new Stack<Character>();
public static void main(String[] args) {
//String exp = "{A+B*(C^D-E)}";
String exp = "a+b*(c^d-e)^(f+g*h)-i";
//String exp="A+b-c*d";
//String exp="(K +L-M*N+(O^P)*W/U/V*T+ Q)";
exp=exp.replaceAll("\\s", "");
System.out.println("Infix Expression: " + exp);
System.out.println(infixToPostfix(exp));
}
static int precedence(char c){
switch(c){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return 0;
}
static String infixToPostfix(String exp){
for(int i=0; i<exp.length(); i++) {
char c = exp.charAt(i);
if(Character.isLetterOrDigit(c)){
result = result+c;
}
else if(c=='('){
stack.push(c);
stack.pop();
}
else if(c==')'){
while(!stack.isEmpty() && stack.peek()!='('){
result=result+stack.peek();
stack.pop();
}
stack.pop();
}
else{
while(!stack.isEmpty() && precedence(c)<=precedence(stack.peek())){
result = result+stack.peek();
stack.pop();
}
stack.push(c);
}
}
while(!stack.isEmpty()){
if(stack.peek()=='('){
return "Invalid Expression ";
}
else{
result=result+stack.peek();
stack.pop();
}
}
return result;
}
}