-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStackPostfix.cpp
More file actions
50 lines (45 loc) · 1019 Bytes
/
StackPostfix.cpp
File metadata and controls
50 lines (45 loc) · 1019 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
return true;
}
return false;
}
int performOperation(int a, int b, char operation) {
if (operation == '+') {
return a + b;
} else if (operation == '-') {
return a - b;
} else if (operation == '*') {
return a * b;
} else if (operation == '/') {
return a / b;
}
return 0;
}
int evaluatePostfix(string expression) {
stack<int> s;
for (int i = 0; i < expression.length(); i++) {
if (!isOperator(expression[i])) {
s.push(expression[i] - '0');
} else {
int a = s.top();
s.pop();
int b = s.top();
s.pop();
int result = performOperation(b, a, expression[i]);
s.push(result);
}
}
return s.top();
}
int main() {
string expression;
cout << "Enter a postfix expression: ";
cin >> expression;
cout << "Result: " << evaluatePostfix(expression) << endl;
return 0;
}