(c语言)后缀表达式

栈 后缀表达式计算请使用已定义好的栈完成后缀表达式计算:
(1)如果是操作数,直接入栈
(2)如果是操作符op,连续出栈两次,得到操作数x 和 y,计算 x op y,并将结果入栈。后缀表达式示例如下:
9 3 1 - 3 * + 10 2 / +
13 445 + 51 / 6 -
操作数、操作符之间由空格隔开,操作符有 +,-,*, /, %共 5 种符号,所有操作数都为整型。栈的定义如下:

#define Stack_Size 50
typedef struct{
    ElemType elem[Stack_Size];
    int top;
}Stack;

bool push(Stack* S, ElemType x);
bool pop(Stack* S, ElemType *x);
void init_stack(Stack *S);

其中,栈初始化的实现为:

void init_stack(Stack *S){
    S->top = -1;
}

实现代码:


int compute_reverse_polish_notation(char* str)
{
    int i = 0;
    Stack Numbers;
    init_stack(&Numbers);
    ElemType number_to_push, num1, num2;
    while (str[i] != '\0') {
        if (str[i] != ' ') {
            if (str[i] >= '0' && str[i] <= '9') {
                number_to_push = 0;
                while (str[i] != ' ' && str[i]) {
                    number_to_push = number_to_push * 10 + (str[i] - '0');
                    i++;
                }
                push(&Numbers, number_to_push);
            } else {
                pop(&Numbers, &num2);
                pop(&Numbers, &num1);
                switch (str[i]) {
                case '+': {
                    num1 += num2;
                    break;
                }
                case '-': {
                    num1 -= num2;
                    break;
                }
                case '*': {
                    num1 *= num2;
                    break;
                }
                case '/': {
                    num1 /= num2;
                    break;
                }
                case '%': {
                    num1 %= num2;
                    break;
                }
                }
                push(&Numbers, num1);
            }
        } 
        i++;
    }
    pop(&Numbers, &num1);
    return num1;
}

猜你喜欢

转载自blog.csdn.net/weixin_45454859/article/details/105101364