//Stack.h #ifndef _STACK_H_ struct StackRecord; typedef struct StackRecord *Stack; #define MinStackSize 3 #define ElementType int struct StackRecord { int Capacity; int TopOfStack; ElementType *Array; }; Stack CreateStack(int MaxElements); void DisposeStack(Stack S); int IsEmpty(Stack S); void MakeEmpty(Stack S); void Push(ElementType X,Stack S); void Pop(Stack S); ElementType Top(Stack S); int IsFull(Stack S); ElementType TopAndPop(Stack S); #endif %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //Stack.c #include<stdio.h> #include<stdlib.h> #include "Stack.h" Stack CreateStack(int MaxElements) { Stack S; if(MaxElements<MinStackSize) { printf("Stack size is too small\n"); } S=malloc(sizeof(struct StackRecord)); if(S==NULL) { printf("Out of space\n"); } S->Array=malloc(sizeof(ElementType)*MaxElements); if(S->Array==NULL) { printf("Out of space\n"); } S->Capacity=MaxElements; S->TopOfStack=-1; MakeEmpty(S); return S; } void DisposeStack(Stack S) { if(S!=NULL) { free(S->Array); //釋放棧 free(S); } } int IsEmpty(Stack S) { return S->TopOfStack==-1; } void MakeEmpty(Stack S) { S->TopOfStack=-1; } void Push(ElementType X,Stack S) { if(IsFull(S)) { printf("Full stack\n"); } else { S->TopOfStack+=1; S->Array[S->TopOfStack]=X; } } void Pop(Stack S) { if(IsEmpty(S)) { printf("Empty of Stack\n"); // return 0; } else { S->TopOfStack--; } } ElementType Top(Stack S) { if(IsEmpty(S)) { printf("Empty of Stack\n"); return 0; } else { ElementType t; t=S->Array[S->TopOfStack]; return t; } } int IsFull(Stack S) { return ((S->TopOfStack)>=(S->Capacity-1)); } ElementType TopAndPop(Stack S) { if(!IsEmpty(S)) { return S->Array[S->TopOfStack--]; } else { printf("Empty of Stack\n"); return 0; } } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //main.c #include<stdio.h> #include "Stack.h" int main(void) { Stack S; S=CreateStack(6); Push(4,S); ElementType x; x=Top(S); printf("%d",x); }