Saturday, 28 September 2024

Write a program to convert infix to postfix using stack

    #include<iostream>

#include<stack>

using namespace std;


int precedence(char op) {

    if(op == '^') return 3;

    else if(op == '*' || op == '/') return 2;

    else if(op == '+' || op == '-') return 1;

    return -1;

}


string infixToPostfix(string infix) {

    stack<char> s;

    string postfix = "";

    for(int i = 0; i < infix.length(); i++) {

        char c = infix[i];

        if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {

            postfix = c+postfix;

        } else if(c == '(') {

            s.push(c);

        } else if(c == ')') {

            while(!s.empty() && s.top() != '(') {

                postfix += s.top();

                s.pop();

            }

            if(!s.empty()) s.pop();

        } else {

      while(!s.empty() && precedence(s.top()) >= precedence(c)) {

                postfix += s.top();

                s.pop();

            }

            s.push(c);

        }

    }

    while(!s.empty()) {

        postfix += s.top();

        s.pop();

    }

    return postfix;

}


int main() {

    string infix;

    cout << "Enter infix expression: ";

    cin >> infix;

    string postfix = infixToPostfix(infix);

    cout << "Postfix expression: " << postfix << endl;

    return 0;

}

Convert the following Infix expression into postfix using a table.

A*(B*C+D*E)+F 

Sr No

Expression

Stack

Postfix

0

A


A

1

*

*

A

2

(

* (

A

3

B

* (

A B

4

*

* ( *

A B

5

C

* ( *

A B C

6

+

* ( +

A B C *

7

D

* ( +

A B C * D

8

*

* ( + *

A B C * D

9

E

* ( + *

A B C * D E

10

)

*

A B C * D E * +

11

+

+

A B C * D E * + *

12

F

+

A B C * D E * + * F

13



A B C * D E * + * F +


A ^ (B – C * D /E) + F


Sr No

Expression

Stack

Postfix

0

A


A

1

^

^

A

2

(

^ (

A

3

B

^ (

A B

4

^ ( –

A B

5

C

^ ( –

A B C

6

*

^ ( – *

A B C

7

D

^ ( – *

A B C D

8

/

^ ( – /

A B C D *

9

E

^ ( – /

A B C D * E

10

)

^

A B C D * E / –

11

+

+

A B C D * E / – ^

12

F

+

A B C D * E / – ^ F

13



A B C D * E / – ^ F +