栈的实现(C语言实现)
程序员文章站
2023-03-22 09:02:12
//头文件
#include
/*====================
栈 数据结构
利用数组实现
====================*/
#define MAX...
//头文件 #include /*==================== 栈 数据结构 利用数组实现 ====================*/ #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;num1bottom=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;itop;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; } }