I have written a program to convert an infix expression to postfix with the help of infix2postfix()
function. Please review my code and suggest ways to make it simpler and more readable.
Code:
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int isOperator(char x)
{
return (x == '-' || x == '+' || x == '/' || x == '*');
}
int precedenceOperator(char x)
{
if (x == '+' || x == '-')
{
return 1;
}
else if (x == '/' || x == '*')
{
return 2;
}
return 0;
}
string infix2Postfix(string infix)
{
int i = 0;
stack<char> lobby;
string postfix;
if (infix.size() == 0)
{
return "";
}
while (infix[i] != '\0')
{
if (!isOperator(infix[i]))
{
postfix = postfix + infix[i];
i++;
}
else
{
while (!lobby.empty() && precedenceOperator(infix[i]) <= precedenceOperator(lobby.top()))
{
postfix += lobby.top();
lobby.pop();
}
lobby.push(infix[i]);
i++;
}
}
while (!lobby.empty())
{
postfix = postfix + lobby.top();
lobby.pop();
}
return postfix;
}
Implementation:
int main()
{
string infix;
cout << "WELCOME TO INFIX TO POSTFIX CONVERTER: " << endl;
cout << "Enter your Infix Expression: ";
getline(cin, infix);
string postfix = infix2Postfix(infix);
cout << "The Postfix Expression is : " << postfix << endl;
return 0;
}
Logic:
- We create a string variable that will hold our postfix expression. Now, start iterating over our infix string. If we receive an operand, concatenate it to the postfix string. Else if we encounter an operator, proceed with the following steps:
- Keep in account the operator and its relative precedence. (We have 4 operators where '/' and '*' hold more precedence than '+' and '-')
- If either the stack is empty or its topmost operator has lower relative precedence, push this operator inside the stack.
- Else, keep popping operators from the stack and concatenate them to the postfix expression until the topmost operator becomes weaker in precedence relative to the current operator.
- If we reach the EOE, pop out every element from the stack, if there is any, and concatenate them as well.