forked from Jasmine-21/Java-FOP
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInfixtoPostfix.java
More file actions
53 lines (47 loc) · 1.45 KB
/
InfixtoPostfix.java
File metadata and controls
53 lines (47 loc) · 1.45 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
import java.util.*;
/*Jasmine*/
class InfixtoPostfix{
public static int getprec(char element) {
//check operand
if (element == '+' || element == '-') {
return 1;
} else if (element == '*' || element == '/') {
return 2;
} else if (element == '^') {
return 3;
} else {
return -1;
}
}
public static void main(String arg[]) {
Stack<Character> s = new Stack<Character>();
Scanner in = new Scanner(System.in);
String exp = in.nextLine(), answer = "";
for (char ch : exp.toCharArray()) {
if (Character.isLetterOrDigit(ch)) {
answer += ch;
} else if (ch == '(') {
s.push('(');
} else if (ch == ')') {
while (s.peek() != '(' && !s.empty()) {
answer += s.pop();
}
if (s.empty()) {
System.out.println("Invalid Expression");
} else {
//pop '('
s.pop();
}
} else {
while (!s.empty() && getprec(ch) <= getprec(s.peek())) {
answer += s.pop();
}
s.push(ch);
}
}
while (!s.empty()) {
answer += s.pop();
}
System.out.println(answer);
}
}