Infix to Prefix Conversion in DSA C++
by DataFlair Team
Program 1
// Program to Convert Infix to Prefix
#include<iostream>
#include<ctype.h>
#include<string.h>
#define clrscr() system("cls")
using namespace std;
char stack[50]; // stack
int top = -1;
void push(char ch)
{
stack[++top] = ch;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char ch)
{
if(ch == '(')
return 0;
if(ch == '+' || ch == '-')
return 1;
if(ch == '*' || ch == '/')
return 2;
return 0;
}
// Function to reverse the string and swap '(' with ')'
void reverseExpr(char expr[])
{
int len = strlen(expr);
for(int i = 0; i < len / 2; i++)
swap(expr[i], expr[len - i - 1]);
for(int i = 0; i < len; i++)
{
if(expr[i] == '(')
expr[i] = ')';
else if(expr[i] == ')')
expr[i] = '(';
}
}
int main()
{
char expr[50]; // expression
char result[50]; // [ ]
int resIndex = 0;
char *p, x;
cout << "Enter the infix expression: ";
cin >> expr; // ( A+B-C*D) // ( D * C - B + A )
// 0 1 2 3 4 5 6 7 8
// Step 1: Reverse the expression and swap parentheses
reverseExpr(expr);
p = expr;
// result[ D C * B - A + ]
// Step 2: Apply infix to postfix logic on reversed expression
while(*p != '\0')
{
if(isalnum(*p))
result[resIndex++] = *p;
else if(*p == '(')
push(*p);
else if(*p == ')')
{
while((x = pop()) != '(')
result[resIndex++] = x;
}
else
{
while(priority(stack[top]) >= priority(*p))
result[resIndex++] = pop();
push(*p);
}
p++;
}
while(top != -1)
result[resIndex++] = pop();
result[resIndex] = '\0';
// Step 3: Reverse the result to get prefix expression
strrev(result); // if not available, use manual reverse loop
cout << "\nPrefix Expression: " << result << endl;
// // result[ D C * B - A + ]
// +A-B*CD
return 0;
}
Tags: convert infix to prefixdsa c++dsa c++ infix to prefix conversiondsa c++ practicaldsa c++ programinfix to prefixinfix to prefix conversion in data structuresinfix to prefix conversion in dsa c++
DataFlair Team
DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.