Infix to Postfix Conversion in Java
Infix to Postfix:
Postfix and prefix expressions are used by compilers to do faster calculations as they support operator precedence in order. An Infix expression is what we humans write mathematical logics as.
Understand what Postfix & Infix is
- Infix Expression: When an operator is in between the two operands
- Example: A * B is known as infix expression.
- Postfix Expression: When operator is after the two operands
- Example: BD * is known as postfix expression.
Algorithm for Infix to Postfix
- Scan infix expression from left to right.
- If there is a character as operand, output it.
- if not
- If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.
- Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.)
- If the scanned character is an ‘(‘, push it to the stack.
- If the character is an ‘)’, pop the stack and and output it until a ‘(‘ is encountered, and discard both the parenthesis.
- Repeat steps 2-6 until infix expression is scanned.
- display the output
- Pop and output from the stack until it is not empty.
All Different variation
For the above implementation we had assumed that expression will only have alphabets as operands and ‘(‘ or ‘)’ as braces.
We will also need to take care of the following
- Operands can be anything alphabets or digits
- Example – a-z or A-Z or 0 – 9
- Brackets can be of different variations { } or [ ] or ( )
Method 1
Method 2
Method 1
Run
import java.util.*; public class Main { public static int precedence(char ch) { if(ch=='+' || ch=='-') return 1; else if(ch=='*' || ch=='/') return 2; // * and / divide have higher precedence. return 0; } public static String convertToPostfix(String exp) { Stack< Character> operators = new Stack<>(); Stack< String> postFix = new Stack<>(); for(int i=0;i < exp.length();i++) { char ch=exp.charAt(i); // current character. if(ch=='(') operators.push(ch); else if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z')) postFix.push(ch+""); else if(ch==')') { while(operators.peek()!= '(') { // STEP 5 of Algorithm. char op = operators.pop(); String first = postFix.pop(); // get the two operands. String second = postFix.pop(); String new_postFix = second+first+op; // add them in reverse order. postFix.push(new_postFix); // push the result to postFix stack again. } operators.pop(); // pop '(' from stack. } // We do the same thing if we get an operator as the current character. else if(ch=='+' || ch=='-' || ch== '*' || ch== '/') { // check precedence of each operator with top of the stack and process them. while(operators.size()>0 && operators.peek()!='(' && precedence(ch) <= precedence(operators.peek())) { char op = operators.pop(); String first = postFix.pop(); String second = postFix.pop(); String new_postFix = second+first+op; postFix.push(new_postFix); } operators.push(ch); } } // If the operator stack still has some elements in it process them too Repeat Step 5. while(operators.size()>0) { char op = operators.pop(); String first = postFix.pop(); String second = postFix.pop(); String new_postFix = second+first+op; postFix.push(new_postFix); } return postFix.pop(); // return resultant Postfix. } public static void main(String args[]) { // We pass Uppercase Infix String infixExpression = "((a+(b*c))-d)"; System.out.println("The Infix Expression is: "+infixExpression); String result = convertToPostfix(infixExpression); System.out.println("The Postfix of the given Infix Expression is: "+result); System.out.println(); } }
Method 2
Run
import java.util.*; class myStack { static final int MAX = 10; int top; char[] a = new char[MAX]; // Maximum size of Stack myStack() { top = -1; } boolean push(char x) { if (top >= (MAX - 1)) { System.out.println("Stack Overflow"); return false; } else { a[++top] = x; return true; } } int pop() { if (top < 0) { System.out.println("Stack Underflow"); return Integer.MIN_VALUE; } else { int x = a[top--]; return x; } } char peek() { if (top < 0) { System.out.println("Stack Underflow"); return 0; } else { char x = a[top]; return x; } } int size(){ return (top+1); } boolean isEmpty(){ return top==-1; } boolean isFull(){ return top == MAX - 1; } } class Main{ static boolean checkIfOperand(char ch) { return Character.isLetterOrDigit(ch); } // Function to compare precedence // If we return larger value means higher precedence static int precedence(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } static StringBuilder covertInfixToPostfix(String expr) { int i; myStack s = new myStack(); StringBuilder result = new StringBuilder(new String("")); for (i = 0; i < expr.length(); ++i) { // Here we are checking is the character we scanned is operand or not // and this adding to output. if (checkIfOperand(expr.charAt(i))) result.append(expr.charAt(i)); // Here, if we scan the character ‘(‘, '[', '{' we need to push it to the stack. else if (expr.charAt(i) == '(' || expr.charAt(i) == '[' || expr.charAt(i) == '{') s.push(expr.charAt(i)); // Here, if we scan character is an ‘)’, we need to pop and print from the stack // do this until an ‘(‘ is encountered in the stack. else if (expr.charAt(i) == ')' || expr.charAt(i) == ']' || expr.charAt(i) == '}') { if(expr.charAt(i) == ')'){ while (!s.isEmpty() && s.peek() != '('){ result.append(s.peek()); s.pop(); } s.pop(); } if(expr.charAt(i) == ']'){ while (!s.isEmpty() && s.peek() != '['){ result.append(s.peek()); s.pop(); } s.pop(); } if(expr.charAt(i) == '}'){ while (!s.isEmpty() && s.peek() != '{'){ result.append(s.peek()); s.pop(); } s.pop(); } } else // if an operator { while (!s.isEmpty() && precedence(expr.charAt(i)) <= precedence(s.peek())){ result.append(s.peek()); s.pop(); } s.push(expr.charAt(i)); } } // Once all initial expression characters are traversed // adding all left elements from stack to exp return result; } // Driver code public static void main(String[] args) { String infixExpression = "((a+(b*c))-d)"; System.out.println("The Infix Expression is: "+infixExpression); StringBuilder result = covertInfixToPostfix(infixExpression); System.out.println("The Postfix of the given Infix Expression is: "+result); } }
Output
The Infix Expression is: ((a+(b*c))-d) The Postfix of the given Infix Expression is: abc*+d-
ADVANTAGE OF POSTFIX:
- Any formula can be expressed without parenthesis.
- It is very convenient for evaluating formulas on computer with stacks.
- Postfix expression doesn’t has the operator precedence.
- Postfix is slightly easier to evaluate.
- It reflects the order in which operations are performed.
- You need to worry about the left and right associativity.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Stacks
- Introduction to Stack in Data Structure
Click Here - Operations on a Stack
Click Here - Stack: Infix, Prefix and Postfix conversions
Click Here - Stack Representation in –
C | C++ | Java - Representation of a Stack as an Array. –
C | C++ | Java - Representation of a Stack as a Linked List. –
C | C++ | Java - Infix to Postfix Conversion –
C | C++ | Java - Infix to prefix conversion in –
C | C++ | Java - Postfix to Prefix Conversion in –
C | C++ | Java
Queues
- Queues in Data Structures (Introduction)
Click Here - Queues Program in C and implementation
Click Here - Implementation of Queues using Arrays | C Program
Click Here - Types of Queues in Data Structure
Click Here - Application of Queue Data Structure
Click Here - Insertion in Queues Program (Enqueuing) –
C | C++ | Java - Deletion (Removal) in Queues Program(Dequeuing) –
C | C++ | Java - Reverse a Queue –
C | C++ | Java - Queues using Linked Lists –
C | C++ | Java - Implement Queue using Stack –
C | C++ | Java - Implement Queue using two Stacks –
C | C++ | Java
Circular Queues
- Circular queue in Data Structure
Click Here - Applications of Circular Queues
Click Here - Circular queue in –
C | C++ | Java - Circular queue using Array –
C | C++ | Java - Circular Queue using Linked Lists –
C | C++ | Java
Priority Queue
Stacks
- Introduction to Stack in Data Structure
- Operations on a Stack
- Stack: Infix, Prefix and Postfix conversions
- Stack Representation in – C | C++ | Java
- Representation of a Stack as an Array. – C | C++ | Java
- Representation of a Stack as a Linked List. – C | C++ | Java
- Infix to Postfix Conversion – C | C++ | Java
- Infix to prefix conversion in – C | C++ | Java
- Postfix to Prefix Conversion in – C | C++ | Java
Queues
- Queues in Data Structures (Introduction)
- Queues Program in C and implementation
- Implementation of Queues using Arrays | C Program
- Types of Queues in Data Structure
- Application of Queue Data Structure
- Insertion in Queues Program (Enqueuing) – C | C++ | Java
- Deletion (Removal) in Queues Program(Dequeuing) – C | C++ | Java
- Reverse a Queue – C | C++ | Java
- Queues using Linked Lists – C | C++ | Java
- Implement Queue using Stack – C | C++ | Java
- Implement Queue using two Stacks – C | C++ | Java
Circular Queues
- Circular queue in Data Structure
- Applications of Circular Queues
- Circular queue in – C | C++ | Java
- Circular queue using Array – C | C++ | Java
- Circular Queue using Linked Lists – C | C++ | Java
Login/Signup to comment