-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy path6-5_Evaluate Postfix Expression (25).c
55 lines (48 loc) · 1.41 KB
/
6-5_Evaluate Postfix Expression (25).c
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
ElementType EvalPostfix(char *expr) {
ElementType stack[Max_Expr+10];
int top = -1;
char *p = expr;
char token[Max_Expr];
while (*p) {
int i = 0;
// Skip spaces
while (*p == ' ') p++;
if (!*p) break;
// Get next token
while (*p && *p != ' ') {
token[i++] = *p++;
}
token[i] = '\0';
// Process token
if (strlen(token) == 1 && (token[0] == '+' || token[0] == '-' || token[0] == '*' || token[0] == '/')) {
// Not enough operands
if (top < 1) return Infinity;
ElementType op2 = stack[top--];
ElementType op1 = stack[top--];
switch (token[0]) {
case '+':
stack[++top] = op1 + op2;
break;
case '-':
stack[++top] = op1 - op2;
break;
case '*':
stack[++top] = op1 * op2;
break;
case '/':
// Division by zero check
if (op2 == 0) return Infinity;
stack[++top] = op1 / op2;
break;
}
} else {
// Convert string to number
ElementType num;
if (sscanf(token, "%lf", &num) != 1) return Infinity;
stack[++top] = num;
}
}
// Final stack should have exactly one value
if (top != 0) return Infinity;
return stack[top];
}