Skip to content

Commit

Permalink
add 6-5
Browse files Browse the repository at this point in the history
  • Loading branch information
tiny656 committed Feb 15, 2025
1 parent 34d6e23 commit 4e23572
Showing 1 changed file with 55 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,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];
}

0 comments on commit 4e23572

Please sign in to comment.