//头文件 #include <stdio.h> /*==================== 栈 数据结构 利用数组实现 ====================*/ #define MAX 100 #define ok 1 #define error 0 typedef 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; } }
原文地址:http://blog.csdn.net/mingyueruya/article/details/43319777