Infix to Postfix in DSA using C++

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;
}

 

courses
Image

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.

Leave a Reply

Your email address will not be published. Required fields are marked *