-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix.java
More file actions
60 lines (58 loc) · 2 KB
/
InfixToPostfix.java
File metadata and controls
60 lines (58 loc) · 2 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
55
56
57
58
59
60
import java.util.Stack;
public class InfixToPostfix {
public static void main(String[] args) {
String infix = "9-(5+3)*4/6";
System.out.println(infix);
Stack<String> val = new Stack<>();
Stack<Character> op = new Stack<>();
for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i);
int ascii = (int) ch;
if (ascii >= 48 && ascii <= 57) {
String s = " " + ch;
val.push(s);
} else if (op.size() == 0 || ch == '(' || op.peek() == '(') {
op.push(ch);
} else if (ch == ')') {
while (op.peek() != '(') {
String v2 = val.pop();
String v1 = val.pop();
char o = op.pop();
String t = v1 + v2 + o;
val.push(t);
}
op.pop();
} else {
if (ch == '+' || ch == '-') {
String v2 = val.pop();
String v1 = val.pop();
char o = op.pop();
String t = v1 + v2 + o;
val.push(t);
op.push(ch);
}
if (ch == '*' || ch == '/') {
if (op.peek() == '*' || op.peek() == '/') {
String v2 = val.pop();
String v1 = val.pop();
char o = op.pop();
String t = v1 + v2 + o;
val.push(t);
op.push(ch);
} else {
op.push(ch);
}
}
}
}
while (val.size() > 1) {
String v2 = val.pop();
String v1 = val.pop();
char o = op.pop();
String t = v1 + v2 + o;
val.push(t);
}
String postfix = val.pop();
System.out.println("Postfix: " + postfix);
}
}