//Stack.h #ifndef _STACK_H_ #define ElementType int struct Node; typedef struct Node *PtrToNode; typedef PtrToNode Stack; struct Node { ElementType Element; PtrToNode Next; }; int IsEmpty(Stack S); Stack CreateStack(void); void MakeEmpty(Stack S); void Push(ElementType X,Stack S); void Pop(Stack S); ElementType Top(Stack S); #endif %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //Stack.c #include<stdio.h> #include "Stack.h" #include<stdlib.h> int IsEmpty(Stack S) { return S->Next==NULL; } Stack CreateStack(void) { Stack S; S=malloc(sizeof(struct Node)); if(S==NULL) { printf("out of space\n"); } S->Next=NULL; return S; } void MakeEmpty(Stack S) { if(S==NULL) { printf("Must use CreateStack first"); } } void Push(ElementType X,Stack S) { Stack TmpCell; TmpCell=malloc(sizeof(struct Node)); if(TmpCell==NULL) { printf("out of space\n"); } else { TmpCell->Next=S->Next; TmpCell->Element=X; S->Next=TmpCell; } } void Pop(Stack S) { PtrToNode TmpCell; if(S==NULL) { printf("Empty of stack\n"); } else { TmpCell=S->Next; S->Next=TmpCell->Next; free(TmpCell); } } ElementType Top(Stack S) { if(S==NULL) { printf("Empty of stack\n"); return 0; } else { return S->Next->Element; } } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //main.c #include<stdio.h> #include<string.h> #include "Stack.h" #define SIZE 50 int Str2num(char *a); //字符串轉換爲數字(目前只寫了整數的轉換) int main(void) { Stack S; ElementType x; //建立空棧 S=CreateStack(); char a[SIZE]; char b[10]; char *d; int i=0; int j=0; printf("請輸入後綴表達式:\n"); d=gets(a); printf("您輸入的是:\n"); puts(a); //打印輸入 if(d!=NULL) { int c=strlen(a); int flag_int=1; int flag_char=1; //printf(" %d ",c); //測試 for(i=0;i<c;i++) { if(a[i]!=' ') { if((a[i]>47)&&(a[i]<58)) { flag_char=0; flag_int=1; b[j]=a[i]; j++; } else if(!(IsEmpty(S) || IsEmpty(S->Next))) { flag_int=0; flag_char=1; int m,n,p; m=Top(S); Pop(S); n=Top(S); Pop(S); if(a[i]==43) { p=m+n; Push(p,S); } if(a[i]==45) { p=m-n; Push(p,S); } if(a[i]==42) { p=m*n; Push(p,S); } if(a[i]==47) { p=m/n; Push(p,S); } printf("\n"); int s; s=Top(S); //Push(p,S); //printf(" 1_2 % d\n",s); } } else { if((flag_int==1)&&(flag_char==0)) { j=0; int dec; //字符串轉換爲數字 dec=Str2num(b); //printf(" 1-1 %d ",dec); //測試用 Push(dec,S); } } } ElementType q; q=Top(S); Pop(S); printf("後綴表達式的值爲:%d\n",q); } } int Str2num(char *a) //字符串轉數字 { int b=strlen(a); int i; int num=0; int m; int power=1; for(i=0;i<b;i++) //測試經過 { m=(a[i]+2)%10; num=(num+m)*10; } num=num/10; return num; }