-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathInfix_To_Postfix_And_Prefix.java
89 lines (72 loc) · 3.34 KB
/
Infix_To_Postfix_And_Prefix.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
import java.io.*;
import java.util.*;
public class Infix_To_Postfix_And_Prefix {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String exp = br.readLine();
Stack<Character> operators = new Stack<>();
Stack<String> postfix = new Stack<>();
Stack<String> prefix = new Stack<>();
for(int i = 0; i < exp.length(); i++){
char ch = exp.charAt(i);
if(ch == '('){
operators.push(ch);
} else if((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <='z') || (ch >= 'A' && ch <='Z')){
prefix.push(ch + "");
postfix.push(ch + "");
} else if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^'){
while(operators.size() > 0 && operators.peek() != '(' && precedence(ch) <= precedence(operators.peek())){
char optor = operators.pop();
String postv2 = postfix.pop();
String postv1 = postfix.pop();
String postv = postv1 + postv2 + optor;
postfix.push(postv);
String prev2 = prefix.pop();
String prev1 = prefix.pop();
String prev = optor + prev1 + prev2;
prefix.push(prev);
}
operators.push(ch);
} else if(ch == ')'){
while(operators.peek() != '('){
char optor = operators.pop();
String postv2 = postfix.pop();
String postv1 = postfix.pop();
String postv = postv1 + postv2 + optor;
postfix.push(postv);
String prev2 = prefix.pop();
String prev1 = prefix.pop();
String prev = optor + prev1 + prev2;
prefix.push(prev);
}
operators.pop();
}
}
while(operators.size() > 0){
char optor = operators.pop();
String postv2 = postfix.pop();
String postv1 = postfix.pop();
String postv = postv1 + postv2 + optor;
postfix.push(postv);
String prev2 = prefix.pop();
String prev1 = prefix.pop();
String prev = optor + prev1 + prev2;
prefix.push(prev);
}
System.out.println(prefix.pop());
System.out.println(postfix.pop());
}
public static int precedence(char optor){
if(optor == '+'){
return 1;
} else if(optor == '-'){
return 1;
} else if(optor == '*'){
return 2;
} else if(optor == '/'){
return 2;
} else{
return 3;
}
}
}