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; }
原文:https://www.cnblogs.com/luanxin/p/9607958.html