Skip to content

Instantly share code, notes, and snippets.

@pbesra
Last active January 17, 2019 11:24
Show Gist options
  • Save pbesra/1fdbe974b5d9a09da8c0c79bae32994d to your computer and use it in GitHub Desktop.
Save pbesra/1fdbe974b5d9a09da8c0c79bae32994d to your computer and use it in GitHub Desktop.
Infix to Post expression | Postfix expression evaluation | C++
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;
// precedence of each operator
bool precedence(char stack_top, char strin){
if(strin=='-'){
if(stack_top=='+' or stack_top=='*' or stack_top=='/' or stack_top=='^'){
return(true);
}
}
if(strin=='+'){
if(stack_top=='-' or stack_top=='*' or stack_top=='/' or stack_top=='^'){
return(true);
}
}else if(strin=='*'){
if(stack_top=='/' or stack_top=='^'){
return(true);
}
}else if(strin=='/'){
if(stack_top=='^'){
return(true);
}
}
return(false);
}
string postfix(string exp){
stack<char> s;
s.push('$'); //initial item in stack
string res=""; // stores postfix expression of infix expression
for(int i=0;i<exp.length();i++){
if(exp[i]>='1' and exp[i]<='9'){
res+=exp[i];
}else if(exp[i]=='('){ // if exp[i]=='(', just push it into the stack
s.push(exp[i]);
}else if(exp[i]==')'){
while(s.top()!='$' and s.top()!='('){
char c=s.top();
res=res+c;
s.pop();
}
if(s.top()=='('){
char c=s.top();
s.pop();
}
}
else{
while(s.top()!='$' and precedence(s.top(), exp[i])){
res=res+s.top();
s.pop();
}
s.push(exp[i]);
}
}
// if there are any more items in the stack, then pop them and append them into res
while(s.top()!='$'){
res+=s.top();
s.pop();
}
return(res);
}
int process(int x, int y, char c){
if(c=='+'){
return(x+y);
}else if(c=='-'){
return(y-x);
}else if(c=='*'){
return(x*y);
}else if(c=='/'){
return(y/x);
}else if(c=='^'){
return((int)pow(y, x));
}
}
// evales postfix expression
void postfixEval(string exp){
stack<int> s;
for(int i=0;i<exp.length();i++){
if(exp[i]>='1' and exp[i]<='9'){
int x=(int)exp[i]-48;
s.push(x);
}else if(exp[i]=='+' or exp[i]=='-' or exp[i]=='*' or exp[i]=='/' or exp[i]=='^'){
if(s.size()>=2){
int x=s.top();
s.pop();
int y=s.top();
s.pop();
int z=process(x, y, exp[i]);
s.push(z);
}
}
cout << s.top() << endl;
}
cout << "final result: " << s.top() << endl;
}
int main(){
string exp="1+2*3+(4*3+3*8/4)-3+6/3";
string s=postfix(exp);
cout << s << endl;
postfixEval(s);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment