-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestion6.cpp
98 lines (79 loc) · 2.17 KB
/
question6.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include<iostream>
using namespace std;
class PostfixEvaluator {
private:
char expression[100];
int stack[100];
int top;
bool isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
void push(int value) {
stack[++top] = value;
}
int pop() {
return stack[top--];
}
int stringToInt(const char* str) {
int result = 0;
while (*str != '\0') {
result = result * 10 + (*str - '0');
str++;
}
return result;
}
public:
PostfixEvaluator() : top(-1) {}
void setExpression(const char* postfixExpr) {
int i = 0;
while (postfixExpr[i] != '\0' && i < 99) {
expression[i] = postfixExpr[i];
i++;
}
expression[i] = '\0';
}
void allocateStack(int size) {
// No dynamic allocation needed since stack is a fixed-size array
}
int evaluate() {
int len = 0;
while (expression[len] != '\0') {
len++;
}
allocateStack(len);
for (int i = 0; i < len; i++) {
if (isdigit(expression[i])) {
push(expression[i] - '0');
} else if (isOperator(expression[i])) {
int operand2 = pop();
int operand1 = pop();
switch (expression[i]) {
case '+':
push(operand1 + operand2);
break;
case '-':
push(operand1 - operand2);
break;
case '*':
push(operand1 * operand2);
break;
case '/':
push(operand1 / operand2);
break;
}
}
}
int result = pop();
return result;
}
};
int main() {
PostfixEvaluator evaluator;
char postfixExpr[100];
cout << "Enter Postfix Expression: ";
cin >> postfixExpr;
evaluator.setExpression(postfixExpr);
int result = evaluator.evaluate();
cout << "Result: " << result << endl;
return 0;
}