Skip to content

Instantly share code, notes, and snippets.

@SohanChy
Last active February 17, 2016 13:24
Show Gist options
  • Select an option

  • Save SohanChy/d6c9f5820b83420d967d to your computer and use it in GitHub Desktop.

Select an option

Save SohanChy/d6c9f5820b83420d967d to your computer and use it in GitHub Desktop.
Evaluation of prefix and postfix notations in CPP
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;
bool isOperator(char x)
{
if(x == '+' || x == '-' || x == '*' || x == '/' || x == '^')
{
return true;
}
return false;
}
int evaluateOperator(int x, int y, char o)
{
if(o == '+')
{
return (x+y);
}
else if(o == '-')
{
return (x-y);
}
else if(o == '/')
{
return (x/y);
}
else if(o == '*')
{
return (x*y);
}
else if(o == '^')
{
return pow(x,y);
}
return -1;
}
int main()
{
/*
PREFIX
*/
stack<int> myStack;
string x = "++2*32/62";
// string x = "22+";
x = '(' + x;
int len = x.length() -1;
// cout<<len;
bool flag = true;
for(int i = len; x[i] != '('; i--)
{
if(x[i] >= '0' && x[i]<= '9')
{
myStack.push(x[i] - 48);
}
else if(myStack.empty())
{
flag = false;
}
else if(isOperator(x[i]))
{
int a = myStack.top();
myStack.pop();
int b = myStack.top();
myStack.pop();
int res = evaluateOperator(a,b,x[i]);
myStack.push(res);
}
}
if(flag)
{
cout<<myStack.top()<<endl;
}
else cout<<"Invalid"<<endl;
/*
POSTFIX
*/
{
stack<int> myStack;
string x = "12+3*6+23+/";
int len = x.length();
x = x + ")";
for(int i =0; i<len && x[i] != ')'; i++)
{
if(x[i]>='0' && x[i]<='9')
{
myStack.push((x[i]-48));
}
else
{
int b = myStack.top();
myStack.pop();
int a = myStack.top();
myStack.pop();
int res = 0;
if(x[i] == '+')
{
res = a + b;
myStack.push(res);
}
else if(x[i] == '-')
{
res = a - b;
myStack.push(res);
}
else if(x[i] == '/')
{
res = a / b;
myStack.push(res);
}
else if(x[i] == '*')
{
res = a * b;
myStack.push(res);
}
else if(x[i] == '^')
{
res = pow(a,b);
myStack.push(res);
}
else
{
cout<<"INVALID CHARACTER IN STRING"<<endl;
break;
}
}
}
cout<<"RESULT: "<<myStack.top()<<endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment