-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLabCycle2-9.cpp
40 lines (35 loc) · 1001 Bytes
/
LabCycle2-9.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
37
38
39
40
#include "LabCycle2-9.h"
#include <stack>
#include <cctype>
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int performOperation(char op, int operand1, int operand2) {
switch (op) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
return 0;
}
}
int evaluatePostfix(const string& postfix) {
stack<int> operands;
for (char c : postfix) {
if (isdigit(c)) {
operands.push(c - '0');
} else if (isOperator(c)) {
int operand2 = operands.top();
operands.pop();
int operand1 = operands.top();
operands.pop();
operands.push(performOperation(c, operand1, operand2));
}
}
return operands.top();
}