//头文件 #include<stdio.h>/*====================栈 数据结构利用数组实现====================*/#define MAX 100#define ok 1#define error 0typedef struct Stack{ int data[MAX]; int top; //栈顶 int bottom; //栈底}Stack,*STACK;//初始化栈int InitStack(STACK stack);//销毁int DestroyStack(STACK stack);//清空int ClearStack(STACK stack);//栈空int StackEmpty(STACK stack);//获取栈顶元素int GetTop(STACK stack,int* elem);//压栈int Push(STACK stack,int* elem);//出栈int Pop(STACK stack,int* elem);//返回栈中元素长度int StackLength(STACK stack,int* len);//打印栈中元素int PrintStack(STACK stack);//栈满int StackFull(STACK stack);
//main函数中实现#include "stack.h"int main(){ int num=10, num1, i=0,j=0; Stack stack; int initFlag=InitStack(&stack); if(!initFlag) return 0; for(num1=0;num1<10;num1++) Push(&stack,&num1);/* int pushFlag=Push(&stack,&num); if(!pushFlag) return 0;*/// ClearStack(&stack); for(;i<10;i++) { int flag=Pop(&stack,&num1); if(flag) printf("%d ",num1); else printf("Pop error"); } int lenFlag=StackLength(&stack,&num1); if(lenFlag) printf("len=%d ",num1); else printf("StackLength error");/* int getFlag=GetTop(&stack,&num1); if(getFlag) printf("%d ",num1);*/ PrintStack(&stack); return 0;}//初始化栈int InitStack(STACK stack){ if(stack==NULL) return error; stack->bottom=stack->top=0; return ok;}//压栈int Push(STACK stack,int* elem){ int flag=StackFull(stack); if(!flag) return error; stack->data[stack->top] =*elem; ++stack->top; return ok;}//打印栈中所有元素int PrintStack(STACK stack){ int i=0; int flag=StackEmpty(stack); if(!flag) return error; for(i=0;i<stack->top;i++) { printf("%d ",stack->data[i]); } printf("\n"); return ok;}//栈空int StackEmpty(STACK stack){ if(stack==NULL || stack->top==stack->bottom) return error; else return ok;}//出栈int Pop(STACK stack,int* elem){ int flag=StackEmpty(stack); if(!flag) return error; *elem=stack->data[stack->top-1]; --stack->top; return ok;}//栈满int StackFull(STACK stack){ if(stack==NULL || stack->top>MAX) return error; else return ok;}//销毁int DestroyStack(STACK stack){ if(stack==NULL) return ok; else { stack->top=stack->bottom; stack=NULL; return ok; }}//清空int ClearStack(STACK stack){ int flag=StackEmpty(stack); if(!flag) return error; else { stack->top=stack->bottom; return ok; }}//获取栈顶元素int GetTop(STACK stack,int* elem){ int flag=StackEmpty(stack); if(!flag) return error; *elem=stack->data[stack->top-1]; return ok;}//返回栈中元素长度int StackLength(STACK stack,int* len){ if(stack==NULL) return error; if(stack->top==stack->bottom) { *len=0; return ok; } else { *len=stack->top; return ok; }}