OneCompiler

infix to postfix

308

#include <iostream>
#include <stack>
#include <cctype>

class Node
{
public:
int data;
Node *next;

Node(int data) : data(data), next(nullptr) {}

};

class Stack
{
private:
Node *top;

public:
Stack() : top(nullptr) {}

void push(int data)
{
    Node *newNode = new Node(data);
    newNode->next = top;
    top = newNode;
}

int pop()
{
    if (isEmpty())
    {
        throw std::runtime_error("Stack is empty");
    }
    int data = top->data;
    Node *temp = top;
    top = top->next;
    delete temp;
    return data;
}

int peek()
{
    if (isEmpty())
    {
        throw std::runtime_error("Stack is empty");
    }
    return top->data;
}

bool isEmpty()
{
    return top == nullptr;
}

};

class InfixToPostfixEvaluator
{
private:
static int precedence(char op)
{
switch (op)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}

public:
static std::string infixToPostfix(const std::string &infixExpression)
{
std::string postfix;
Stack stack;
for (char c : infixExpression)
{
if (std::isalnum(c))
{
postfix += c;
}
else if (c == '(')
{
stack.push(c);
}
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
postfix += stack.pop();
}
stack.pop(); // Remove the '('
}
else
{
while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek()))
{
postfix += stack.pop();
}
stack.push(c);
}
}
while (!stack.isEmpty())
{
postfix += stack.pop();
}
return postfix;
}

static int evaluatePostfix(const std::string &postfixExpression)
{
    Stack stack;
    for (char c : postfixExpression)
    {
        if (std::isdigit(c))
        {
            stack.push(c - '0');
        }
        else
        {
            int operand2 = stack.pop();
            int operand1 = stack.pop();
            switch (c)
            {
            case '+':
                stack.push(operand1 + operand2);
                break;
            case '-':
                stack.push(operand1 - operand2);
                break;
            case '*':
                stack.push(operand1 * operand2);
                break;
            case '/':
                stack.push(operand1 / operand2);
                break;
            }
        }
    }
    return stack.pop();
}

};

int main()
{
std::string infixExpression = "3+5*(2-8)/2";
std::string postfixExpression = InfixToPostfixEvaluator::infixToPostfix(infixExpression);
std::cout << "Infix Expression: " << infixExpression << std::endl;
std::cout << "Postfix Expression: " << postfixExpression << std::endl;
int result = InfixToPostfixEvaluator::evaluatePostfix(postfixExpression);
std::cout << "Result of postfix expression: " << result << std::endl;

return 0;

}