// ======== ADT the representation of the STACK(Sequential Storage) ======== //#ifndef STACK_H_#define STACK_H_#include<stdbool.h>#define STACK_INIT_SIZE 5#define STACKINCREMENT 1#define OK 1#define ERROR 0#define OVERFLOW -1typedefint Elem;typedefstruct{
Elem *base;
Elem *top;int stacksize;//int length;}Stack;//Initialize the stackvoidInitStack(Stack *S);//destroy the stackvoidDestroyStack(Stack *S);//clear the stackvoidClearStack(Stack *S);//determine if the stack is empty
bool IsEmpty(Stack S);//return the length of the stackunsignedintLength(Stack S);//return the top of the stack
Elem Top(Stack S);//push e on the stack
bool Push(Stack *S, Elem e);//pop the stack
bool Pop(Stack *S);#endif
Stack.c
#include<stdio.h>#include<stdlib.h>#include"Stack.h"#include<string.h>//Initialize the stackvoidInitStack(Stack *S){
S->base =(Elem*)malloc(STACK_INIT_SIZE *sizeof(Elem));memset(S->base,0, STACK_INIT_SIZE *sizeof(Elem));if(!S->base)exit(OVERFLOW);
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;}//destroy the stackvoidDestroyStack(Stack *S){free(S->base);
S->stacksize =0;
S->base =NULL;
S->top =NULL;}//clear the stackvoidClearStack(Stack *S){
S->top = S->base;}//determine if the stack is empty
bool IsEmpty(Stack S){return S.top == S.base;}//return the length of the stackunsignedintLength(Stack S){return S.top - S.base;}//return the top of the stack
Elem Top(Stack S){return*(S.top -1);}//push e on the stack
bool Push(Stack *S, Elem e){if(S->top - S->base +1>= S->stacksize){
S->base =(Elem*)realloc(S->base,(STACK_INIT_SIZE + STACKINCREMENT)*sizeof(Elem));
S->stacksize += STACKINCREMENT;printf("increment\n");}if(!S->base)exit(OVERFLOW);*(S->top)= e;
S->top++;return OK;}//pop the stack
bool Pop(Stack *S){if(IsEmpty(*S)){printf("fail\n");exit(OVERFLOW);}
S->top--;return OK;}
main.c
#include<stdio.h>#include"Stack.h"int main (){
Stack S1;InitStack(&S1);Push(&S1,1);Push(&S1,2);Push(&S1,3);Push(&S1,4);Push(&S1,5);
Stack S2;InitStack(&S2);Push(&S2,1);Push(&S2,2);Push(&S2,3);Push(&S2,4);Push(&S2,5);while(!IsEmpty(S2)){printf("%d\n",Top(S2));Pop(&S2);}//Pop(&S2);printf("the length of the stack is %d\n",Length(S1));printf("the top of the stack is %d\n",Top(S1));Pop(&S1);printf("the top of the stack is %d\n",Top(S1));DestroyStack(&S1);DestroyStack(&S2);return0;}