栈(表达式求值)

这里只说明一点,注意栈的元素是先进后出(后进先出)的,在运算的时候,注意运算符前后的数字

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define ERROR 0
#define OK 1

typedef struct Stack {
    int *elements;
    int max_size, top_index;
} Stack;

void init(Stack *s, int length) {
    s->elements = (int *)malloc(sizeof(int) * length);
    s->max_size = length;
    s->top_index = -1;
}

int push(Stack *s, int element) {
    if (s->top_index >= s->max_size - 1) {
        return ERROR;
    }
    s->top_index++;
    s->elements[s->top_index] = element;
    return OK;
}

int pop(Stack *s) {
    if (s->top_index < 0) {
        return ERROR;
    }
    s->top_index--;
    return OK;
}

int top(Stack *s) {
    return s->elements[s->top_index];
}

int empty(Stack *s) {
    if (s->top_index < 0) {
        return 1;
    } else {
        return 0;
    }
}

int precede(char a, char b) {
    if((a == '*' || a == '/') && (b == '+' || b == '-')){
		return 1;
    }else{
        return 0;
    }
}
int operate(char theta, int a, int b) {
    switch(theta){
        case '*': return a*b;break;
        case '/': return b/a;break;
        case '+': return a+b;break;
        case '-': return b-a;break;
    }
}
void calc(Stack *numbers, Stack *operators) {
    int a = top(numbers);
    pop(numbers);
    int b = top(numbers);
    pop(numbers);
    push(numbers, operate(top(operators), a, b));
    pop(operators);
}

void clear(Stack *s) {
    free(s->elements);
    free(s);
}

int main() {
    int n;
    scanf("%d", &n);
    Stack *numbers = (Stack *)malloc(sizeof(Stack));
    init(numbers, n);
    Stack *operates = (Stack *)malloc(sizeof(Stack));
    init(operates, n);
    char *buffer = (char *)malloc(sizeof(char) * (n + 1));
    scanf("%s", buffer);
    int i = 0;
    while(i < n){
        if(isdigit(buffer[i])){
			push(numbers, buffer[i] - '0');
            i++;
        }else{
            if(empty(operates) || precede(buffer[i], top(operates))){
                push(operates, buffer[i]);
                i++;
            }else{
                calc(numbers, operates);
            }
        }
    }
    while(!empty(operates)){
        calc(numbers, operates);
    }
    printf("%d\n", top(numbers));
    clear(numbers);
    clear(operates);
    free(buffer);
    return 0;
}
发布了48 篇原创文章 · 获赞 5 · 访问量 753

猜你喜欢

转载自blog.csdn.net/weixin_43899266/article/details/104306726