Open In App

Infix to Postfix Conversion using Stack in C++

Infix expression is a common way of writing mathematical expressions where operators are written between the operands whereas postfix is a type of expression in which a pair of operands is followed by an operator. In this article, we will learn how to use a stack to convert an infix expression to a postfix expression in C++.

Example:

Input:
Infix expression: “A+B*C”

Output:
Postfix expression: “ABC*+”

Infix to Postfix Conversion using Stack in C++

To convert an infix expression to a postfix expression using a std::stack in C++, we can follow the below approach:

Approach:

C++ Program to Convert an Infix Expression to a Postfix Expression using a Stack

The following program illustrates how we can convert an infix expression to a postfix expression using a stack in C++.

// C++ Program to illustrate how to use a stack to convert
// an infix expression to a postfix expression
#include <iostream>
#include <stack>
#include <string>
using namespace std;

// Function to check the precedence of operators
int precedence(char op)
{
    if (op == '+' || op == '-')
        return 1;
    if (op == '*' || op == '/')
        return 2;
    return 0;
}

// Function to convert infix expression to postfix
// expression
string infixToPostfix(string infix)
{
    stack<char> st;
    string postfix = "";
    for (int i = 0; i < infix.length(); i++) {
        char c = infix[i];

        // If the scanned character is an operand, add it to
        // output string.
        if (isalnum(c))
            postfix += c;

        // If the scanned character is an '(', push it to
        // the stack.
        else if (c == '(')
            st.push('(');

        // If the scanned character is an ')', pop and to
        // output string from the stack until an '(' is
        // encountered.
        else if (c == ')') {
            while (st.top() != '(') {
                postfix += st.top();
                st.pop();
            }
            st.pop();
        }

        // If an operator is scanned
        else {
            while (!st.empty()
                   && precedence(c)
                          <= precedence(st.top())) {
                postfix += st.top();
                st.pop();
            }
            st.push(c);
        }
    }

    // Pop all the remaining elements from the stack
    while (!st.empty()) {
        postfix += st.top();
        st.pop();
    }

    return postfix;
}

int main()
{
    string infix = "A+B*C";
    cout << "Infix Expression: " << infix << endl;
    cout << "Postfix Expression: " << infixToPostfix(infix)
         << endl;
    return 0;
}

Output
Infix Expression: A+B*C
Postfix Expression: ABC*+

Time Complexity: O(N), here N is the length of infix expression.
Auxiliary Space: O(N)

Article Tags :