
- DSA - Home
- DSA - Overview
- DSA - Environment Setup
- DSA - Algorithms Basics
- DSA - Asymptotic Analysis
- Data Structures
- DSA - Data Structure Basics
- DSA - Data Structures and Types
- DSA - Array Data Structure
- DSA - Skip List Data Structure
- Linked Lists
- DSA - Linked List Data Structure
- DSA - Doubly Linked List Data Structure
- DSA - Circular Linked List Data Structure
- Stack & Queue
- DSA - Stack Data Structure
- DSA - Expression Parsing
- DSA - Queue Data Structure
- DSA - Circular Queue Data Structure
- DSA - Priority Queue Data Structure
- DSA - Deque Data Structure
- Searching Algorithms
- DSA - Searching Algorithms
- DSA - Linear Search Algorithm
- DSA - Binary Search Algorithm
- DSA - Interpolation Search
- DSA - Jump Search Algorithm
- DSA - Exponential Search
- DSA - Fibonacci Search
- DSA - Sublist Search
- DSA - Hash Table
- Sorting Algorithms
- DSA - Sorting Algorithms
- DSA - Bubble Sort Algorithm
- DSA - Insertion Sort Algorithm
- DSA - Selection Sort Algorithm
- DSA - Merge Sort Algorithm
- DSA - Shell Sort Algorithm
- DSA - Heap Sort Algorithm
- DSA - Bucket Sort Algorithm
- DSA - Counting Sort Algorithm
- DSA - Radix Sort Algorithm
- DSA - Quick Sort Algorithm
- Matrices Data Structure
- DSA - Matrices Data Structure
- DSA - Lup Decomposition In Matrices
- DSA - Lu Decomposition In Matrices
- Graph Data Structure
- DSA - Graph Data Structure
- DSA - Depth First Traversal
- DSA - Breadth First Traversal
- DSA - Spanning Tree
- DSA - Topological Sorting
- DSA - Strongly Connected Components
- DSA - Biconnected Components
- DSA - Augmenting Path
- DSA - Network Flow Problems
- DSA - Flow Networks In Data Structures
- DSA - Edmonds Blossom Algorithm
- DSA - Maxflow Mincut Theorem
- Tree Data Structure
- DSA - Tree Data Structure
- DSA - Tree Traversal
- DSA - Binary Search Tree
- DSA - AVL Tree
- DSA - Red Black Trees
- DSA - B Trees
- DSA - B+ Trees
- DSA - Splay Trees
- DSA - Range Queries
- DSA - Segment Trees
- DSA - Fenwick Tree
- DSA - Fusion Tree
- DSA - Hashed Array Tree
- DSA - K-Ary Tree
- DSA - Kd Trees
- DSA - Priority Search Tree Data Structure
- Recursion
- DSA - Recursion Algorithms
- DSA - Tower of Hanoi Using Recursion
- DSA - Fibonacci Series Using Recursion
- Divide and Conquer
- DSA - Divide and Conquer
- DSA - Max-Min Problem
- DSA - Strassen's Matrix Multiplication
- DSA - Karatsuba Algorithm
- Greedy Algorithms
- DSA - Greedy Algorithms
- DSA - Travelling Salesman Problem (Greedy Approach)
- DSA - Prim's Minimal Spanning Tree
- DSA - Kruskal's Minimal Spanning Tree
- DSA - Dijkstra's Shortest Path Algorithm
- DSA - Map Colouring Algorithm
- DSA - Fractional Knapsack Problem
- DSA - Job Sequencing with Deadline
- DSA - Optimal Merge Pattern Algorithm
- Dynamic Programming
- DSA - Dynamic Programming
- DSA - Matrix Chain Multiplication
- DSA - Floyd Warshall Algorithm
- DSA - 0-1 Knapsack Problem
- DSA - Longest Common Sub-sequence Algorithm
- DSA - Travelling Salesman Problem (Dynamic Approach)
- Hashing
- DSA - Hashing Data Structure
- DSA - Collision In Hashing
- Disjoint Set
- DSA - Disjoint Set
- DSA - Path Compression And Union By Rank
- Heap
- DSA - Heap Data Structure
- DSA - Binary Heap
- DSA - Binomial Heap
- DSA - Fibonacci Heap
- Tries Data Structure
- DSA - Tries
- DSA - Standard Tries
- DSA - Compressed Tries
- DSA - Suffix Tries
- Treaps
- DSA - Treaps Data Structure
- Bit Mask
- DSA - Bit Mask In Data Structures
- Bloom Filter
- DSA - Bloom Filter Data Structure
- Approximation Algorithms
- DSA - Approximation Algorithms
- DSA - Vertex Cover Algorithm
- DSA - Set Cover Problem
- DSA - Travelling Salesman Problem (Approximation Approach)
- Randomized Algorithms
- DSA - Randomized Algorithms
- DSA - Randomized Quick Sort Algorithm
- DSA - Karger’s Minimum Cut Algorithm
- DSA - Fisher-Yates Shuffle Algorithm
- Miscellaneous
- DSA - Infix to Postfix
- DSA - Bellmon Ford Shortest Path
- DSA - Maximum Bipartite Matching
- DSA Useful Resources
- DSA - Questions and Answers
- DSA - Selection Sort Interview Questions
- DSA - Merge Sort Interview Questions
- DSA - Insertion Sort Interview Questions
- DSA - Heap Sort Interview Questions
- DSA - Bubble Sort Interview Questions
- DSA - Bucket Sort Interview Questions
- DSA - Radix Sort Interview Questions
- DSA - Cycle Sort Interview Questions
- DSA - Quick Guide
- DSA - Useful Resources
- DSA - Discussion
Convert Infix expression to Postfix expression
Infix to postfix conversion rearranges math expressions to make them easier for computers to evaluate. In infix notation, operators are between operands (e.g., "A + B"). In postfix notation, operators come after operands (e.g., "A B +"). We use a stack to convert infix to postfix, ensuring the order of operations is preserved.
What is Infix, Postfix, and Prefix?
Before jumping into conversion, lets understand the three common types of expressions:
- Infix: The operator is placed between operands. Example:
A + B
- Postfix (Reverse Polish Notation): The operator comes after the operands. Example:
A B +
- Prefix (Polish Notation): The operator comes before the operands. Example:
+ A B
Postfix notation is useful because it eliminates the need for parentheses and follows a simple evaluation process using stacks.
Why Use a Stack for Conversion?
Stacks helps us to manage the order of operations (precedence) and parentheses correctly. When scanning an infix expression, we can use a stack to store operators and pop them based on precedence. This way, we can convert infix to postfix without losing the order of operations.
Infix to Postfix Conversion Algorithm
The algorithm for converting an infix expression to a postfix expression using a stack is:
Read the expression from left to right. 1. If an operand (A-Z, 0-9) is encountered, add it directly to the output. 2. If an operator is encountered: 1. Pop operators from the stack to the output if they have higher or equal precedence. 2. Push the current operator onto the stack. 3. If an opening parenthesis(
is found, push it onto the stack. 4. If a closing parenthesis)
is found, pop operators from the stack to the output until an opening parenthesis is encountered. 5. After scanning the entire expression, pop any remaining operators from the stack to the output.
Operator Precedence
Operators have different levels of precedence, which determine the order of evaluation:
^
(Exponentiation) Highest precedence*, /
(Multiplication, Division) Higher precedence+, -
(Addition, Subtraction) Lowest precedence
When two operators have the same precedence, we evaluate them based on associativity. Most operators are left-to-right associative, except exponentiation, which is right-to-left.
Example: Convert Infix to Postfix
Let's convert the infix expression: A + B * C
Step | Scanned Character | Stack | Postfix Expression |
---|---|---|---|
1 | A | - | A |
2 | + | + | A |
3 | B | + | A B |
4 | * | + * | A B |
5 | C | + * | A B C |
6 | - | - | A B C * + |
Final Postfix Expression: A B C * +
Evaluating Postfix Expression
Now that we have converted infix to postfix, lets see how to evaluate it:
- Read the postfix expression from left to right.
- If an operand is found, push it to the stack.
- If an operator is found, pop the last two operands from the stack, apply the operation, and push the result back.
- Continue until the expression is fully processed. The final value in the stack is the result.
Code for Infix to Postfix Conversion
Now that we already know the algorithm, lets see how to implement it in C, C++, Java and Python:
#include <stdio.h> #include <string.h> #include <ctype.h> #define MAX 100 char stack[MAX]; int top = -1; void push(char item) { if (top == (MAX - 1)) printf("Stack Overflow\n"); else stack[++top] = item; } char pop() { if (top == -1) { printf("Stack Underflow\n"); return '\0'; } return stack[top--]; } int precedence(char symbol) { switch (symbol) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } void infixToPostfix(char infix[], char postfix[]) { int i = 0, j = 0; char symbol; push('('); strcat(infix, ")"); while (infix[i] != '\0') { symbol = infix[i]; if (symbol == ' ') { i++; continue; } if (symbol == '(') push(symbol); else if (isalnum(symbol)) postfix[j++] = symbol; else if (symbol == ')') { while (top != -1 && stack[top] != '(') postfix[j++] = pop(); pop(); } else { while (top != -1 && precedence(stack[top]) >= precedence(symbol)) postfix[j++] = pop(); push(symbol); } i++; } postfix[j] = '\0'; } int main() { char infix[MAX] = "A + B * C"; char postfix[MAX]; printf("Infix Expression: %s\n", infix); infixToPostfix(infix, postfix); printf("Postfix Expression: %s\n", postfix); return 0; }
Output
Following is the output of the above code:
Enter Infix Expression: A + B * C Postfix Expression: ABC*+
#include <iostream> #include <stack> #include <string> using namespace std; int precedence(char symbol) { switch (symbol) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } string infixToPostfix(string infix) { stack<char> s; string postfix = ""; s.push('('); infix += ')'; for (int i = 0; i < infix.length(); i++) { char symbol = infix[i]; if (symbol == ' ') continue; if (symbol == '(') s.push(symbol); else if (isalnum(symbol)) postfix += symbol; else if (symbol == ')') { while (s.top() != '(') { postfix += s.top(); s.pop(); } s.pop(); } else { while (precedence(s.top()) >= precedence(symbol)) { postfix += s.top(); s.pop(); } s.push(symbol); } } return postfix; } int main() { string infix = "A + B * C"; cout << "Infix Expression: " << infix << endl; string postfix = infixToPostfix(infix); cout << "Postfix Expression: " << postfix << endl; return 0; }
Output
Following is the output of the above code:
Infix Expression: A + B * C Postfix Expression: ABC*+
import java.util.Stack; public class InfixToPostfix { public static int precedence(char symbol) { switch (symbol) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } public static String infixToPostfix(String infix) { Stack<Character> s = new Stack<>(); String postfix = ""; s.push('('); infix += ')'; for (int i = 0; i < infix.length(); i++) { char symbol = infix.charAt(i); if (symbol == ' ') continue; if (symbol == '(') s.push(symbol); else if (Character.isLetterOrDigit(symbol)) postfix += symbol; else if (symbol == ')') { while (s.peek() != '(') { postfix += s.peek(); s.pop(); } s.pop(); } else { while (precedence(s.peek()) >= precedence(symbol)) { postfix += s.peek(); s.pop(); } s.push(symbol); } } return postfix; } public static void main(String[] args) { String infix = "A + B * C"; System.out.println("Infix Expression: " + infix); String postfix = infixToPostfix(infix); System.out.println("Postfix Expression: " + postfix); } }
Output
Following is the output of the above code:
Infix Expression: A + B * C Postfix Expression: ABC*+
def precedence(symbol): if symbol == '^': return 3 elif symbol in ['*', '/']: return 2 elif symbol in ['+', '-']: return 1 else: return 0 def infix_to_postfix(infix): stack = [] postfix = "" stack.append('(') infix += ')' for symbol in infix: if symbol == ' ': continue if symbol == '(': stack.append(symbol) elif symbol.isalnum(): postfix += symbol elif symbol == ')': while stack[-1] != '(': postfix += stack.pop() stack.pop() else: while precedence(stack[-1]) >= precedence(symbol): postfix += stack.pop() stack.append(symbol) return postfix infix = "A + B * C" print("Infix Expression:", infix) postfix = infix_to_postfix(infix) print("Postfix Expression:", postfix)
Output
Following is the output of the above code:
Infix Expression: A + B * C Postfix Expression: ABC*+
Applications of Postfix Notation
Following are some common applications of postfix notation:
- Used in compilers to evaluate expressions without needing parentheses.
- Helps in designing calculators where stack-based evaluation is required.
- Used in Expression Trees for easy computation.
Conclusion
Infix notation is how we naturally write mathematical expressions, but computers prefer postfix because its easier to process. We can use stack for easy Infix to Postfix conversion. Understanding this concept is crucial for solving problems related to expression evaluation and compiler design.