用c语言写一个顺序栈关于后缀表达式运算代码
时间: 2023-11-06 14:06:12 浏览: 36
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef struct {
double data[MAX_STACK_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
void push(Stack *s, double x) {
if (is_full(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
double pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
double evaluate_postfix(char *expr) {
Stack s;
init(&s);
double op1, op2, result;
char *p = expr;
while (*p != '\0') {
if (isdigit(*p)) {
push(&s, *p - '0');
} else if (*p == '+' || *p == '-' || *p == '*' || *p == '/') {
op2 = pop(&s);
op1 = pop(&s);
switch (*p) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
}
push(&s, result);
}
p++;
}
return pop(&s);
}
int main() {
char expr[] = "23+4*";
double result = evaluate_postfix(expr);
printf("Result: %f\n", result);
return 0;
}