Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created January 14, 2020 19:15
Show Gist options
  • Select an option

  • Save misterpoloy/10310ae1374c56cc18ee85034b020d1f to your computer and use it in GitHub Desktop.

Select an option

Save misterpoloy/10310ae1374c56cc18ee85034b020d1f to your computer and use it in GitHub Desktop.
Evaluate Postfix Expression using Stack
#include <iostream>
#include <string>
#include <stack>
bool isOperator(char x) {
if (x == '+' || x == '-' || x == '*' || x == '/' )
return true;
return false;
}
bool isNumber(char x) {
if (x >= '0' && x <= '9') return true;
return false;
}
int performOperation(char operation, int op1, int op2) {
if (operation == '+') return op1 + op2;
if (operation == '-') return op1 - op2;
if (operation == '*') return op1 * op2;
if (operation == '/') return op1 / op2;
return -1;
}
double evaluatePostfix(std::string exp) {
std::stack<int> S;
for (int i = 0; i < exp.length(); i++) {
if (exp[i] == ' ' || exp[i] == ',')
continue;
if (isNumber(exp[i])) {
int digit = 0;
while (i < exp.length() && isNumber(exp[i])) {
// *10 is necessary for multiple numbers base 10
digit = digit * 10 + exp[i] - '0'; // - '0' is a hack to convert ASCII chart to INT
i++;
}
i--;
S.push(digit);
}
if (isOperator(exp[i])) {
int op1 = S.top(); S.pop();
int op2 = S.top(); S.pop();
int result = performOperation(exp[i], op1, op2);
S.push(result);
}
}
return S.top();
}
int main() {
std::string exp = "1 12 2*+";
double result = evaluatePostfix(exp);
std::cout << result << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment