字尾表示式的計算--For初學者
阿新 • • 發佈:2018-12-12
上次寫了中綴轉字尾,這次來計算字尾表示式的值,書接上文click here。 思路很簡單,先掃描輸入的字尾表示式,遇到數字就進棧,遇到運算子就出兩個棧頂的元素運算,運算的結果再入棧。直到掃描完,並且棧內只剩下一個元素,進行輸出。 描繪的可能不清楚,直接上程式碼:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 typedef int ElemType; typedef struct node { ElemType date; struct node *next; } StackNode; void InitStack(StackNode **p) {//棧的宣告 (*p)=NULL; } int StackEmpty(StackNode *p) {//如果棧是空的返回0;不空返回1 if(p==NULL) return 0; return 1; } void Push(StackNode **top, ElemType x) {//入棧操作 StackNode *p; p=(StackNode *)malloc(sizeof(StackNode)); p->date=x; p->next=*top; *top=p; } void Pop(StackNode **top, ElemType *x) {//出棧操作 StackNode *p; if(*top==NULL) printf("Stack is empty!\n"); else{ *x=(*top)->date; p=*top; *top=(*top)->next; free(p); } } int Calc(char *s) { StackNode *p; InitStack(&p); ElemType x1,x2; int i=0,x; while(s[i])//進行四則運算 { if(s[i]>='0'&&s[i]<='9') Push(&p,s[i]-48); else{ Pop(&p,&x1); Pop(&p,&x2); if(s[i]=='+') Push(&p,x1+x2); if(s[i]=='-') Push(&p,x1-x2); if(s[i]=='*') Push(&p,x1*x2); if(s[i]=='/') Push(&p,x1/x2); } i++; } return p->date; } int main() { // (5+3)*2+(6+3) = 25 char str[100] = "53+2*63++";//讀者可以自行更改 int rst; rst = Calc(str); printf("the results is: %d\n", rst); return 0; }
本人能力有限,執行時難免有bug,請正確輸入,輸入的數要在10以內,因為字元只能識別一個,為了方便,我在主函式中定義了字尾表示式,讀者可以自行更改
附上結果執行圖: