Pages

Sunday, July 13, 2025

Infix to Postfix Conversion using C++

#include <iostream>

#include <stack>

#include <string>

using namespace std;


int precedence(char op) {

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

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

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

    return -1;

}


string infixToPostfix(string s) {

    stack<char> st;

    string result;


    for(char c : s) {

        if(isalnum(c)) {

            result += c;

        }

        else if(c == '(') {

            st.push(c);

        }

        else if(c == ')') {

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

                result += st.top(); st.pop();

            }

            st.pop(); // remove '('

        }

        else { // operator

            while(!st.empty() && precedence(c) <= precedence(st.top())) {

                result += st.top(); st.pop();

            }

            st.push(c);

        }

    }


    while(!st.empty()) {

        result += st.top(); st.pop();

    }


    return result;

}


No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...