VOOZH about

URL: https://www.geeksforgeeks.org/cpp/infix-to-postfix-conversion-using-stack-in-cpp/

⇱ Infix to Postfix Conversion using Stack in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Infix to Postfix Conversion using Stack in C++

Last Updated : 23 Jul, 2025

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:

  • Create an empty stack for storing operators and a string for storing the result.
  • Scan the infix expression from left to right.
  • If the scanned character is an operand, append it to the result.
  • If the scanned character is an operator, pop operators from the stack to the result until the top of the stack has an operator of lower precedence or the stack is empty, then push the scanned operator onto the stack.
  • If the scanned character is ‘(’, push it onto the stack.
  • If the scanned character is ‘)’, pop operators from the stack to the result until ‘(’ is encountered, and pop ‘(’ from the stack.
  • After all characters are scanned, pop the remaining operators from the stack to the result.

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++.


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)

Comment
Article Tags: