forked from noodles-sed/Simple-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.cpp
More file actions
28 lines (26 loc) · 689 Bytes
/
postfix.cpp
File metadata and controls
28 lines (26 loc) · 689 Bytes
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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int evaluatePostfix(string exp) {
stack<int> s;
for (char c : exp) {
if (isdigit(c))
s.push(c - '0');
else {
int val2 = s.top(); s.pop();
int val1 = s.top(); s.pop();
switch (c) {
case '+': s.push(val1 + val2); break;
case '-': s.push(val1 - val2); break;
case '*': s.push(val1 * val2); break;
case '/': s.push(val1 / val2); break;
}
}
}
return s.top();
}
int main() {
string exp = "231*+9-";
cout << "Result: " << evaluatePostfix(exp);
}