Infix to Postfix in DSA using C++
by DataFlair Team
Program 1
// Program to Convert infix to Postfix
#include<iostream>
#include<ctype.h>
#define clrscr() system("cls")
using namespace std;
char stack[50];
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;
}
int main()
{
char expr[50];
char *p, x;
cout<<"Enter the expression : ";
cin>>expr;
cout<<endl;
p = expr;
while(*p != '\0')
{
if(isalnum(*p))
printf("%c ",*p);
else if(*p == '(')
push(*p);
else if(*p == ')')
{
while((x = pop()) != '(')
cout<<x;
}
else
{
while(priority(stack[top]) >= priority(*p))
cout<<pop();
push(*p);
}
p++;
}
while(top != -1)
{
cout<<pop();
}
return 0;
}
Tags: dsa c++dsa c++ practicaldsa c++ programdsa c++ program on infix to postfixdsa using c++infix to postfix in dsa c++infix to postfix in dsa using 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.