You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Infix is the day to day notation that we use of format A + B type. The general form can be classified as (a op b) where a and b are operands(variables) and op is Operator.
4
+
5
+
# Postfix Notation
6
+
7
+
Postfix is notation that compiler uses/converts to while reading left to right and is of format AB+ type. The general form can be classified as (ab op) where a and b are operands(variables) and op is Operator.
8
+
9
+
## Code
10
+
11
+
```
12
+
import java.util.Stack;
13
+
14
+
public class InfixtoPostfix {
15
+
public static void main(String[] args) {
16
+
String exp = "a+b*(c^d-e)^(f+g*h)-i";
17
+
System.out.println(infixToPostfix(exp));
18
+
}
19
+
public static int Precidense(char ch) {
20
+
switch (ch){
21
+
case '+':
22
+
case '-':
23
+
return 1;
24
+
25
+
case '*':
26
+
case '/':
27
+
return 2;
28
+
29
+
case '^':
30
+
return 3;
31
+
}
32
+
return -1;
33
+
}
34
+
35
+
public static String infixToPostfix(String exp) {
36
+
String result = "";
37
+
Stack<Character> stack = new Stack<>();
38
+
39
+
for (char c:exp.toCharArray()) {
40
+
if (Character.isLetterOrDigit(c))
41
+
result += c;
42
+
else if (c == '(')
43
+
stack.push(c);
44
+
else if (c == ')') {
45
+
while (!stack.isEmpty() && stack.peek() != '(')
46
+
result += stack.pop();
47
+
stack.pop();
48
+
}
49
+
else {// an operator is encountered
50
+
while (!stack.isEmpty() && Precidense(c) <= Precidense(stack.peek()))
0 commit comments