-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix.java
More file actions
41 lines (40 loc) · 1.1 KB
/
InfixToPostfix.java
File metadata and controls
41 lines (40 loc) · 1.1 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
import Stack.Stack;
public class InfixToPrefix{
public static void main(String[] args) {
String expression = "(A+B*C/D-E+F/G/(H+I))";
Stack s = new Stack();
String reversePolish = "";
s.push('(');
expression += ")";
for (int i=0;i<expression.length();i++) {
while(stackPrecident((char)s.peek()) > inputPrecident(expression.charAt(i)) ){
reversePolish += (char)s.pop();
}
if (stackPrecident((char)s.peek()) != inputPrecident(expression.charAt(i)) ) {
s.push(expression.charAt(i));
}
else{
s.pop();
}
}
System.out.println(reversePolish);
}
static int inputPrecident(char ch){
if (ch == '+' || ch == '-') return 1;
if (ch == '*' || ch == '/') return 3;
if (ch == '^' || ch == '$') return 6;
if (Character.isLetter(ch) || (ch >= '0' && ch <= '9'))
return 7;
if (ch == '(') return 9;
return 0;
}
static int stackPrecident(char ch){
if (ch == '+' || ch == '-') return 2;
if (ch == '*' || ch == '/') return 4;
if (ch == '^' || ch == '$') return 5;
if (Character.isLetter(ch) || (ch >= '0' && ch <= '9'))
return 8;
if (ch == '(') return 0;
return 0;
}
}