Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create infix-to-postfix.md #467

Merged
merged 1 commit into from
Oct 4, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions Java/Stack/infix-to-postfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Infix Notation

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.

# Postfix Notation

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.

## Code

```
import java.util.Stack;

public class InfixtoPostfix {
public static void main(String[] args) {
String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(exp));
}
public static int Precidense(char ch) {
switch (ch){
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

public static String infixToPostfix(String exp) {
String result = "";
Stack<Character> stack = new Stack<>();

for (char c:exp.toCharArray()) {
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
stack.push(c);
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();
stack.pop();
}
else {// an operator is encountered
while (!stack.isEmpty() && Precidense(c) <= Precidense(stack.peek()))
result += stack.pop();
stack.push(c);
}

}
while (!stack.isEmpty()){
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
return result;
}
}
```