Infix to Prefix conversion using two stacks
Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2).
Example : (A+B) * (C-D)
Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )
Given an Infix expression, convert it into a Prefix expression using two stacks.
Examples:
Input : A * B + C / D Output : + * A B/ C D Input : (A - B/C) * (A/K-L) Output : *-A/BC-/AKL
The idea is to use one stack for storing operators and other to store operands. The stepwise algo is:
- Traverse the infix expression and check if given character is an operator or an operand.
- If it is an operand, then push it into operand stack.
- If it is an operator, then check if priority of current operator is greater than or less than or equal to the operator at top of the stack. If priority is greater, then push operator into operator stack. Otherwise pop two operands from operand stack, pop operator from operator stack and push string operator + operand1 + operand 2 into operand stack. Keep popping from both stacks and pushing result into operand stack until priority of current operator is less than or equal to operator at top of the operator stack.
- If current character is ‘(‘, then push it into operator stack.
- If current character is ‘)’, then check if top of operator stack is opening bracket or not. If not pop two operands from operand stack, pop operator from operator stack and push string operator + operand1 + operand 2 into operand stack. Keep popping from both stacks and pushing result into operand stack until top of operator stack is an opening bracket.
- The final prefix expression is present at top of operand stack.
Below is the implementation of above algorithm:
C++
// CPP program to convert infix to prefix. #include <bits/stdc++.h> using namespace std; // Function to check if given character is // an operator or not. bool isOperator(char c) { return (!isalpha(c) && !isdigit(c)); } // Function to find priority of given // operator. int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Function that converts infix // expression to prefix expression. string infixToPrefix(string infix) { // stack for operators. stack<char> operators; // stack for operands. stack<string> operands; for (int i = 0; i < infix.length(); i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (!operators.empty() && operators.top() != '(') { // operand 1 string op1 = operands.top(); operands.pop(); // operand 2 string op2 = operands.top(); operands.pop(); // operator char op = operators.top(); operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. string tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket from // stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.push(string(1, infix[i])); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (!operators.empty() && getPriority(infix[i]) <= getPriority(operators.top())) { string op1 = operands.top(); operands.pop(); string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); string tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix[i]); } } // Pop operators from operators stack // until it is empty and add result // of each pop operation in // operands stack. while (!operators.empty()) { string op1 = operands.top(); operands.pop(); string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); string tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands.top(); } // Driver code int main() { string s = "(A-B/C)*(A/K-L)"; cout << infixToPrefix(s); return 0; } |
Java
// Java program to convert // infix to prefix. import java.util.*; class GFG { // Function to check if // given character is // an operator or not. static boolean isOperator(char c) { return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z')); } // Function to find priority // of given operator. static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Function that converts infix // expression to prefix expression. static String infixToPrefix(String infix) { // stack for operators. Stack<Character> operators = new Stack<Character>(); // stack for operands. Stack<String> operands = new Stack<String>(); for (int i = 0; i < infix.length(); i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix.charAt(i) == '(') { operators.push(infix.charAt(i)); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix.charAt(i) == ')') { while (!operators.empty() && operators.peek() != '(') { // operand 1 String op1 = operands.peek(); operands.pop(); // operand 2 String op2 = operands.peek(); operands.pop(); // operator char op = operators.peek(); operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. String tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket // from stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix.charAt(i))) { operands.push(infix.charAt(i) + ""); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (!operators.empty() && getPriority(infix.charAt(i)) <= getPriority(operators.peek())) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix.charAt(i)); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (!operators.empty()) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands.peek(); } // Driver code public static void main(String args[]) { String s = "(A-B/C)*(A/K-L)"; System.out.println( infixToPrefix(s)); } } // This code is contributed // by Arnab Kundu |
C#
// C# program to convert // infix to prefix. using System; using System.Collections.Generic; public class GFG { // Function to check if // given character is // an operator or not. static bool isOperator(char c) { return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z')); } // Function to find priority // of given operator. static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Function that converts infix // expression to prefix expression. static String infixToPrefix(String infix) { // stack for operators. Stack<char> operators = new Stack<char>(); // stack for operands. Stack<String> operands = new Stack<String>(); for (int i = 0; i < infix.Length; i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.Push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (operators.Count!=0 && operators.Peek() != '(') { // operand 1 String op1 = operands.Peek(); operands.Pop(); // operand 2 String op2 = operands.Peek(); operands.Pop(); // operator char op = operators.Peek(); operators.Pop(); // Add operands and operator // in form operator + // operand1 + operand2. String tmp = op + op2 + op1; operands.Push(tmp); } // Pop opening bracket // from stack. operators.Pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.Push(infix[i] + ""); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (operators.Count!=0 && getPriority(infix[i]) <= getPriority(operators.Peek())) { String op1 = operands.Peek(); operands.Pop(); String op2 = operands.Peek(); operands.Pop(); char op = operators.Peek(); operators.Pop(); String tmp = op + op2 + op1; operands.Push(tmp); } operators.Push(infix[i]); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (operators.Count!=0) { String op1 = operands.Peek(); operands.Pop(); String op2 = operands.Peek(); operands.Pop(); char op = operators.Peek(); operators.Pop(); String tmp = op + op2 + op1; operands.Push(tmp); } // Final prefix expression is // present in operands stack. return operands.Peek(); } // Driver code public static void Main() { String s = "(A-B/C)*(A/K-L)"; Console.WriteLine( infixToPrefix(s)); } } // This code is contributed by 29AjayKumar |
*-A/BC-/AKL
Time Complexity: O(n)
Auxiliary Space: O(n)
Recommended Posts:
- Prefix to Infix Conversion
- Convert Infix To Prefix Notation
- Postfix to Prefix Conversion
- Prefix to Postfix Conversion
- Postfix to Infix
- Stack | Set 2 (Infix to Postfix)
- Check if the two given stacks are same
- Queue using Stacks
- Bubble sort using two Stacks
- Sorting array using Stacks
- Implement two stacks in an array
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Sudo Placement[1.3] | Playing with Stacks
- Find maximum sum possible equal sum of three stacks
- Merging and Sorting Two Unsorted Stacks
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



