#include <iostream>
#include <stack>
using namespace std;
int precedence(char c)
{
if (c == '^') return 3;
else if(c=='*'|| c=='/') return 2;
else if(c=='+'|| c=='-') return 1;
else return -1;
}
string InfixToPostfix(string str)
{
stack<char>Stack;
string result;
// add sentinal at end of infix exp
str = str + ')';
Stack.push('(');
for (int i = 0; i<str.length(); i++)
{
char ch = str[i];
if (isdigit(ch))
{
result += ch;
}
else if (ch == '(' )
{
Stack.push(ch);
}
else if(ch == ')')
{
while (Stack.top() != '(')
{
result += Stack.top();
Stack.pop();
}
Stack.pop(); //Pop '('
}
else
{
while(!Stack
.empty()) && (precedence
(ch
) <= precedence
(Stack
.top
())) {
result += Stack.top();
Stack.pop();
}
Stack.push(ch);
}
}
return result;
}
int main()
{
string st = "(5*(6+2) - (2/4))";
cout << "postfix exp"<< InfixToPostfix(st);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RhY2s+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgcHJlY2VkZW5jZShjaGFyIGMpCnsKICAgIGlmIChjID09ICdeJykgIHJldHVybiAzOwogICAgZWxzZSBpZihjPT0nKid8fCBjPT0nLycpIHJldHVybiAyOwogICAgZWxzZSBpZihjPT0nKyd8fCBjPT0nLScpIHJldHVybiAxOwogICAgZWxzZSByZXR1cm4gLTE7Cn0KCnN0cmluZyBJbmZpeFRvUG9zdGZpeChzdHJpbmcgc3RyKQp7CiAgICBzdGFjazxjaGFyPlN0YWNrOwogICAgc3RyaW5nIHJlc3VsdDsKICAgIAogICAgLy8gYWRkIHNlbnRpbmFsIGF0IGVuZCBvZiBpbmZpeCBleHAKICAgIHN0ciA9IHN0ciArICcpJzsKICAgIAogICAgU3RhY2sucHVzaCgnKCcpOwoKICAgIGZvciAoaW50IGkgPSAwOyBpPHN0ci5sZW5ndGgoKTsgaSsrKSAKICAgIHsKICAgICAgICBjaGFyIGNoID0gc3RyW2ldOwogICAgICAgIGlmIChpc2RpZ2l0KGNoKSkKICAgICAgICB7CiAgICAgICAgICAgIHJlc3VsdCArPSBjaDsKICAgICAgICB9CiAgICAgICAgZWxzZSBpZiAoY2ggPT0gJygnICkKICAgICAgICB7CiAgICAgICAgICAgIFN0YWNrLnB1c2goY2gpOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmKGNoID09ICcpJykKICAgICAgICB7CiAgICAgICAgICAgIHdoaWxlIChTdGFjay50b3AoKSAhPSAnKCcpCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIHJlc3VsdCArPSBTdGFjay50b3AoKTsKICAgICAgICAgICAgICAgIFN0YWNrLnBvcCgpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIFN0YWNrLnBvcCgpOyAvL1BvcCAnKCcKICAgICAgICB9CiAgICAgICAgZWxzZQogICAgICAgIHsKICAgICAgICAgICAgd2hpbGUoIVN0YWNrLmVtcHR5KCkpICYmIChwcmVjZWRlbmNlKGNoKSA8PSBwcmVjZWRlbmNlKFN0YWNrLnRvcCgpKSkKICAgICAgICAgICAgewogICAgICAgICAgICAgICAgcmVzdWx0ICs9IFN0YWNrLnRvcCgpOwogICAgICAgICAgICAgICAgU3RhY2sucG9wKCk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgU3RhY2sucHVzaChjaCk7CiAgICAgICAgfQogICAgfQogICAgcmV0dXJuIHJlc3VsdDsKfQoKaW50IG1haW4oKQp7CiAgICBzdHJpbmcgc3QgPSAiKDUqKDYrMikgLSAoMi80KSkiOwogICAgY291dCA8PCAicG9zdGZpeCBleHAiPDwgSW5maXhUb1Bvc3RmaXgoc3QpOwogICAgcmV0dXJuIDA7Cgp9