23栈的应用-根据后缀表达式求值

Posted luanxin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了23栈的应用-根据后缀表达式求值相关的知识,希望对你有一定的参考价值。

main.c

#define _CRT_SECURE_NO_WARNING

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"Stack.h"

//判断是不是数字
int IsNumber1(char c) {
    return c >= 0 && c <= 9;
}

typedef struct MYNUM {
    StackNode node;
    int val;
}MyNum;


int Caculate(int left,int right,char c) {
    
    int ret = 0;
    switch (c) {
    case+:
        ret = left + right;
        break;
    case-:
        ret = left - right;
        break;
    case*:
        ret = left*right;
        break;
    case/:
        ret = left / right;
        break;
    default:
        break;
    }
    return ret;
}


int main()
{
    char* str = "831-5*+";
    char* p = str;

    LinkStack* stack = InitStack();

    while (*p!=) {
        if (IsNumber1(*p)) {
            MyNum* num = (MyNum*)malloc(sizeof(MyNum));
            num->val = *p - 0;

            Push(stack, num);

        }
        else {

            //先从栈中弹出右操作数
            MyNum* right = (MyNum*)GetTop(stack);
            int rightNum = right->val;
            Pop(stack);
            free(right);
            //取出左操作数
            MyNum* left = (MyNum*)GetTop(stack);
            int leftNum = left->val;
            Pop(stack);
            free(left);

            int ret = Caculate(leftNum, rightNum, *p);
            //结果入栈
            MyNum* num = (MyNum*)malloc(sizeof(MyNum));
            num->val = ret;
            Push(stack,num);
        }
        p++;
    }

    if (StackLength(stack) == 1) {
        MyNum* num = (MyNum*)GetTop(stack);
        printf("运算结果是:%d
",num->val);
        Pop(stack);
        free(num);
    }

    //释放栈
    DestoryStack(stack);

    printf("
");
    system("pause");
    return 0;
}

 

以上是关于23栈的应用-根据后缀表达式求值的主要内容,如果未能解决你的问题,请参考以下文章

栈的典型应用-表达式求值

栈的应用四则运算表达式求值

数据结构----栈与队列之栈的应用四则运算表达式求值

C语言 任意表达式求值。(栈的应用

中缀表达式转换成后缀表达式并求值

数据结构之栈的应用:中缀表达式求值