-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathExercise1310_InfixToPostfix.java
43 lines (43 loc) · 1.84 KB
/
Exercise1310_InfixToPostfix.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
public class Exercise1310_InfixToPostfix {
public static void main(String[] args) {
Stack<String> ops = new Stack<String>();
Stack<String> stringsStack = new Stack<String>();
String string = "1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )";
String[] arr = string.split(" ");
for (String s: arr) {
if (s.equals("("));
else if (s.equals("+"))ops.push(s);
else if (s.equals("-"))ops.push(s);
else if (s.equals("*"))ops.push(s);
else if (s.equals("/"))ops.push(s);
else if (s.equals(")")) {
String op = ops.pop();
if (op.equals("+")) {
String rightOperand = stringsStack.pop();
String leftOperand = stringsStack.pop();
stringsStack.push("( " + leftOperand + " " + rightOperand + " + ) ") ;
}
else if (op.equals("-")) {
String rightOperand = stringsStack.pop();
String leftOperand = stringsStack.pop();
stringsStack.push("( " + leftOperand + " " + rightOperand + " - ) ") ;
}
else if (op.equals("*")){
String rightOperand = stringsStack.pop();
String leftOperand = stringsStack.pop();
stringsStack.push("( " + leftOperand + " " + rightOperand + " * ) ") ;
}
else if (op.equals("/")){
String rightOperand = stringsStack.pop();
String leftOperand = stringsStack.pop();
stringsStack.push("( " + leftOperand + " " + rightOperand + " / ) ") ;
}
} else {
stringsStack.push(s);
}
}
for (String s: stringsStack){
StdOut.print(s);
}
}
}