栈的复习(加减乘除表达式求值)

输入格式
输入一共有两行,第一行为一个整数 m(1≤m≤100),代表表达式中一共有 m 个字符。
第二行的输入为一个表达式,表达式中只包含若干个整数以及+,-,*,/四种运算符。

输出格式
输出只有一行,即输入的表达式的计算结果。

#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) {
    if (theta == '+') {
        return a + b;
    } else if (theta == '-') {
        return a - b;
    } else if (theta == '*') {
        return a * b;
    } else {
        return a / b;
    }
}
void calc(Stack *numbers, Stack *operators) {
    int b = top(numbers);
   // printf("b = %d\n",top(numbers));
    pop(numbers);
   
    int a = top(numbers);
   // printf("a = %d\n",top(numbers));
    pop(numbers);
    
    push(numbers, operate(top(operators), a, b));
    //printf("%d\n",operate(top(operators), a, b));
    
    pop(operators);
}

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

int main() {
    int m;
    scanf("%d", &m);
    Stack *numbers = (Stack *)malloc(sizeof(Stack));
    init(numbers, m);
    Stack *operators = (Stack *)malloc(sizeof(Stack));
    init(operators, m);
    char *buffer = (char *)malloc(sizeof(char) * (m + 1));
    scanf("%s", buffer);
    int i = 0;
    while (i < m) {
        if (isdigit(buffer[i])) {
            push(numbers, buffer[i] - '0');
            i++;
        } else {
            if (empty(operators) || precede(buffer[i], top(operators))) {
                 push(operators, buffer[i]);
                i++;
            }
           else {
               calc(numbers, operators);
               
           }
        }
    }
    while (!empty(operators)) {
        calc(numbers, operators);
       
    }
    printf("%d", top(numbers));
    clear(numbers);
    clear(operators);
    free(buffer);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yitahutu79

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值