码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-09-08 10:29:37      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:print   typedef   运算   ack   取出   int   def   turn   break   

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、栈的应用-根据后缀表达式求值

标签:print   typedef   运算   ack   取出   int   def   turn   break   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!