-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem36.c
More file actions
72 lines (59 loc) · 1.72 KB
/
problem36.c
File metadata and controls
72 lines (59 loc) · 1.72 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LEN 10000
#define MAX_TOKEN 1000
int isOperator(const char *token) {
return strcmp(token, "+") == 0 || strcmp(token, "-") == 0 ||
strcmp(token, "*") == 0 || strcmp(token, "/") == 0;
}
int toInt(const char *str) {
return atoi(str);
}
int applyOperator(int a, int b, const char *op) {
if (strcmp(op, "+") == 0) return a + b;
if (strcmp(op, "-") == 0) return a - b;
if (strcmp(op, "*") == 0) return a * b;
if (strcmp(op, "/") == 0) return a / b;
return 0;
}
int main() {
char input[MAX_LEN + 1];
char *tokens[MAX_TOKEN];
int tokenCount = 0;
printf("Enter the postfix expression: ");
if (fgets(input, sizeof(input), stdin) == NULL) {
printf("Error reading input.\n");
return 1;
}
size_t len = strlen(input);
if (len > 0 && input[len - 1] == '\n') input[len - 1] = '\0';
char *token = strtok(input, " ");
while (token != NULL && tokenCount < MAX_TOKEN) {
tokens[tokenCount++] = token;
token = strtok(NULL, " ");
}
int stack[MAX_TOKEN];
int top = -1;
for (int i = 0; i < tokenCount; i++) {
if (isOperator(tokens[i])) {
if (top < 1) {
printf("Not enough operands for operator");
return 1;
}
int b = stack[top--];
int a = stack[top--];
int result = applyOperator(a, b, tokens[i]);
stack[++top] = result;
} else {
stack[++top] = toInt(tokens[i]);
}
}
if (top != 0) {
printf("!! Invalid Expression !!\n");
return 1;
}
printf("Result: %d\n", stack[top]);
return 0;
}