Data structures-Lab-Programs-II BCA A-PROGRAM 5
Data structures-Lab-Programs-II BCA A-PROGRAM 5
ON
2024
Material Prepared
By
G.T. BAKYARAJ, B.Com., MCA., MBA., MFT.,
Assistant Professor
Department of Computer Science
Peri College of Arts and Science, Mannivakkam, Chennai-600048.
Program 5
Aim: To Convert infix to postfix expressions using c++ program using stack.
Algorithm:
1. Initialize:
Create an empty stack for operators.
Initialize an empty string for the postfix expression.
2. Process Each Character:
If the character is an operand: Append it directly to the postfix expression.
If the character is an opening parenthesis: Push it onto the stack.
If the character is a closing parenthesis: Pop characters from the stack to the
postfix expression until an opening parenthesis ( is encountered. Remove the
opening parenthesis from the stack.
3. If the character is an operator:
While the stack is not empty and the precedence of the current operator is less than or
equal to the precedence of the operator at the top of the stack:
a. Pop the operator from the stack to the postfix expression.
b. Push the current operator onto the stack.
4. Finalize:
Pop any remaining operators from the stack to the postfix expression.
5. Return:
Return the postfix expression.
Source Code:
#include <iostream> // For input and output
#include <stack> // To use the stack data structure
#include <string> // For handling strings
using namespace std;
int main() {
string infix = "A+B*C"; // Example infix expression
// Output the original infix expression
cout << "The Infix expression: " << infix << endl;
// Output the corresponding postfix expression
cout << "The Postfix expression: " << infixToPostfix(infix) << endl;
return 0;
}
Output: