棧的應用_字尾表示式的求解
阿新 • • 發佈:2018-12-13
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> #include "LinkStack.h" bool IsNumber(char c) { return c >= '0'&&c <= '9'; } bool IsOperator(char c){ return c == '+' || c == '-' || c == '*' || c == '/'; } typedef struct MYNUM { LinkNode node; int val; }Mynum; int caculate(int left, int right, char c){ switch (c) { case '+': return left + right; break; case '-': return left - right; break; case '/': return left / right; break; case '*': return left *right; break; default: break; } } int main(void){ char *str = "831-5*+"; LinkStack*stack = Init_LinkStack(); char*p = str; while (*p!='\0') { //如果式數字 直接入棧 if (IsNumber(*p)) { Mynum*num = (Mynum*)malloc(sizeof(Mynum)); num->val = *p - '0'; Push_LinkStack(stack,(LinkNode*)num); } else { //如果式表示式 則將棧頂元素彈出做為右運算元 int rihhtnum = ((Mynum*)Top_LinkStack(stack))->val; Pop_LinkStack(stack); //如果式表示式 則將棧頂元素彈出做為左運算元 int Lefenum = ((Mynum*)Top_LinkStack(stack))->val; Pop_LinkStack(stack); //計算此操作符,將計算結果入棧 int ret= caculate(Lefenum ,rihhtnum,*p); Mynum*num = (Mynum*)malloc(sizeof(Mynum)); num->val = ret; Push_LinkStack(stack, (LinkNode*)num); } p++; } //最後棧裡只剩一個元素 即 計算結果 Mynum*result= (Mynum*)Top_LinkStack(stack); printf("%d",result->val ); free(result); FreeSpace_LinkStack(stack); system("pause"); return 0; }