-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluatePostfix.cpp
36 lines (31 loc) · 915 Bytes
/
evaluatePostfix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <cmath>
using namespace std;
int evaluatePostfix(string postfix) {
stack<int> s;
for (char ch : postfix) {
if (isdigit(ch)) {
s.push(ch - '0');
} else {
int op2 = s.top(); s.pop();
int op1 = s.top(); s.pop();
switch (ch) {
case '+': s.push(op1 + op2); break;
case '-': s.push(op1 - op2); break;
case '*': s.push(op1 * op2); break;
case '/': s.push(op1 / op2); break;
case '^': s.push(pow(op1, op2)); break;
default: cout << "Invalid operator" << endl; return -1;
}
}
}
return s.top();
}
int main() {
string postfix = "23*54*+9-";
cout << "Result of postfix evaluation: " << evaluatePostfix(postfix) << endl;
return 0;
}