-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixToPostfix.java
82 lines (66 loc) · 2.2 KB
/
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
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
import java.util.Scanner;
import java.util.Stack;
public class InfixToPostfix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String exp = "(A+B^C^D)*(E+F/G))";
System.out.println("Postfix expression is: " + postfix(exp));
}
public static String postfix(String exp) {
Stack<Character> stack = new Stack<Character>();
String postfix = "";
stack.push('(');
for (int i = 0; i < exp.length(); i++) {
char ch = exp.charAt(i);
if (Character.isLetterOrDigit(ch)) {
postfix += ch;
}else if (ch == '(') {
stack.push(ch);
}else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix += stack.pop();
}
stack.pop();
} else {
if(ch=='^'){
while (!stack.isEmpty() && precedence(ch) < precedence(stack.peek())) {
postfix += stack.pop();
}
stack.push(ch);
}
else{
while (!stack.isEmpty() && precedence(ch) <= precedence(stack.peek())) {
postfix += stack.pop();
}
stack.push(ch);
}
}
}
// while (!stack.isEmpty()) {
// postfix += stack.pop();
// }
return postfix;
}
public static int precedence(char ch) {
if (ch == '^') {
return 4;
}else if (ch == '*' || ch == '/' || ch == '%') {
return 2;
}else if (ch == '+' || ch == '-') {
return 1;
}else {
return 0;
}
}
public static int Inputprecedence(char ch) {
if (ch == '^') {
return 3;
}else if (ch == '*' || ch == '/' || ch == '%') {
return 2;
}else if (ch == '+' || ch == '-') {
return 1;
}else {
return 0;
}
}
}