P56 例3-4 设有后缀算术表达式ABCD/-E*+,其中,变量A等于3,变量B等于6,变量C等于4,变量D等于2,变量E等于5,设计一个程序,求出该后缀算数表达式的值。
头文件:LinStack.h
#include<stdio.h> #include<stdlib.h> #include<ctype.h> typedef int DataType; typedef struct snode { DataType data; struct snode *next; }LSNode; void StackInitiate(LSNode **head) { *head=(LSNode *)malloc(sizeof(LSNode)); (*head)->next=NULL; } int StackNotEmpty(LSNode *head) { if(head->next==NULL) return 0; else return 1; } int StackPush(LSNode *head,DataType x) { LSNode *p; p=(LSNode *)malloc(sizeof(LSNode)); p->data=x; p->next=head->next; head->next=p; return 1; } int StackPop(LSNode *head,DataType *d) { LSNode *p=head->next; if(p==NULL) { printf("堆栈已空出错!"); return 0; } head->next=p->next; *d=p->data; free(p); return 1; } int StackTop(LSNode *head,DataType *d) { LSNode *p=head->next; if(p=NULL) { printf("堆栈已空出错!"); return 0; } *d=p->data; return 1; } void Destroy(LSNode *head) { LSNode *p,*p1; p=head; while(p!=NULL) { p1=p; p=p->next; free(p1); } }源文件:例3-4.c
#include"LinStack.h" int PostExp(char str[]) { DataType x,x1,x2; int i; LSNode *head; StackInitiate(&head); for(i=0;str[i]!='#';i++) { if(isdigit(str[i])) { x=(int)(str[i]-48); StackPush(head,x); } else { StackPop(head,&x2); StackPop(head,&x1); switch(str[i]) { case '+': { x1+=x2; break; } case '-': { x1-=x2; break; } case '*': { x1*=x2; break; } case '/': { if(x2==0.0) { printf("除数为0错!\n"); exit(0); } else { x1/=x2; break; } } } StackPush(head,x1); } } StackPop(head,&x); return x; } int main() { char str[]="3642/-5*+#"; int result; result=PostExp(str); printf("后缀算术表达式计算结果为:%d",result); return 0; }