首页 > 其他 > 详细

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

时间:2018-09-08 10:04:43      阅读:160      评论:0      收藏:0      [点我收藏+]

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!=\0) {
        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\n",num->val);
        Pop(stack);
        free(num);
    }

    //释放栈
    DestoryStack(stack);

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

 

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

原文:https://www.cnblogs.com/luanxin/p/9607958.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!