Skip to content

Commit 1db6543

Browse files
Merge pull request codemistic#467 from tanuj1811/patch-1
Create infix-to-postfix.md
2 parents a2488ee + cd326d8 commit 1db6543

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Java/Stack/infix-to-postfix.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Infix Notation
2+
3+
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()))
51+
result += stack.pop();
52+
stack.push(c);
53+
}
54+
55+
}
56+
while (!stack.isEmpty()){
57+
if(stack.peek() == '(')
58+
return "Invalid Expression";
59+
result += stack.pop();
60+
}
61+
return result;
62+
}
63+
}
64+
```

0 commit comments

Comments
 (0)