Skip to content

Instantly share code, notes, and snippets.

@anantbahuguna
Created January 3, 2020 20:49
Show Gist options
  • Save anantbahuguna/4288621d5013c7188cb6303051900245 to your computer and use it in GitHub Desktop.
Save anantbahuguna/4288621d5013c7188cb6303051900245 to your computer and use it in GitHub Desktop.
Infix to Postfix C++ Program
#include<bits/stdc++.h>
using namespace std;
//Assuming each operand and operator is of 1 character instead of multiple characters
bool IsOpeningParenthesis(char optr)
{
if(optr == '(' || optr == '{' || optr == '[')
return true;
else
return false;
}
bool IsClosingParenthesis(char optr)
{
if(optr == ')' || optr == '}' || optr == ']')
return true;
else
return false;
}
bool HasHigherPrecedence(char top,char curr_exp)
{
map<char,int> precede_map;
precede_map['+']= 0;
precede_map['-']= 0;
precede_map['*']= 1;
precede_map['/']= 1;
if(precede_map[top] >= precede_map[curr_exp])
return true;
else
return false;
}
string InfixToPostfix(string exp)
{
stack<int> s;
string post;
for(int i = 0;i< exp.length();i++)
{
if(isalnum(exp[i]))
post.push_back(exp[i]);
else if(!IsOpeningParenthesis(exp[i]) && !IsClosingParenthesis(exp[i]))
{
while(!s.empty() && !IsOpeningParenthesis(s.top()) && HasHigherPrecedence(s.top(),exp[i]))
{
post.push_back(s.top());
s.pop();
}
s.push(exp[i]);
}
else if(IsOpeningParenthesis(exp[i]))
s.push(exp[i]);
else if(IsClosingParenthesis(exp[i]))
{
while(!s.empty() && !IsOpeningParenthesis(s.top()))
{
post.push_back(s.top());
s.pop();
}
s.pop();
}
}
while(!s.empty())
{
post.push_back(s.top());
s.pop();
}
return post;
}
int main()
{
string exp;
getline(cin,exp);
cout<<InfixToPostfix(exp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment