1.[代码][C/C++]代码
#include
#include
#include "./base/stack.h"
struct T{
int id;
int age;
};
int main(int argc, char **argv){
stack *sta;
struct T *p;
sta = stack_create();
stack_set_max_size(sta,1000);
stack_status(sta);
int i=0;
for(i=0;i<1000;i++){
p = (struct T*)malloc(sizeof(struct T));
p->id=i;
p->age = 20+i;
stack_push(sta,p);
}
stack_status(sta);
for(i=0;i<1000;i++){
p = stack_pop(sta);
//printf("%d\n",p->id);
}
stack_status(sta);
stack_destory(sta);
}
2.[文件] stack.h ~ 737B 下载(7)
typedef struct node{
struct node *down;
void *val;
}node;
typedef struct stack{
int size;
int max_size;
node *top;
/*操作val相关的api函数*/
void (*free) (void* val);
void (*dup) (void* val);
void (*match)(void* val_1,void*val_2);
}stack;
/*创建一个栈,默认栈大小为10000000*/
stack *stack_create();
void stack_set_max_size(stack *sta,int size);
/*添加一个元素*/
int stack_push(stack *sta,void *val);
/*取一个元素*/
void *stack_pop(stack *sta);
/*栈是否为空*/
int stack_is_empty(stack *sta);
/*栈是否满了*/
int stack_is_full(stack *sta);
/*销毁栈*/
void stack_destory(stack *sta);
/*栈的状态*/
void stack_status(stack *sta);
3.[文件] stack.c ~ 2KB 下载(9)
#include
#include
#include "stack.h"
#define STACK_MAX_SIZE 10000000
stack *stack_create(){
stack *sta = (stack*)malloc(sizeof(stack));
sta->size = 0;
sta->max_size = STACK_MAX_SIZE;
sta->top = NULL;
return sta;
}
void stack_set_max_size(stack *sta,int size){
if(stack_is_empty(sta) && size
sta->max_size = size;
}
int stack_push(stack *sta,void *val){
if(stack_is_full(sta)){
printf("[ warning ] stack is full\n");
return 0 ;
}
node *p = (node*)malloc(sizeof(node));
if(p==NULL) return 0;
p->down = sta->top;
p->val = val;
sta->top= p;
sta->size ++;
return 1;
}
void *stack_pop(stack *sta){
if(stack_is_empty(sta)){
return NULL;
}else{
node *n = sta->top;
sta->top = n->down;
sta->size --;
return n->val;
}
}
int stack_is_empty(stack *sta){
return sta->size==0 ? 1 : 0;
}
void stack_destory(stack *sta){
if(stack_is_empty(sta)){
free(sta);
}else{
node *tmp= sta->top;
node *p = NULL;
while(tmp){
p = tmp;
if(sta->free) sta->free(tmp->val);
free(p);
tmp = tmp->down;
}
free(sta);
}
}
int stack_is_full(stack *sta){
return sta->size == sta->max_size ? 1 : 0;
}
void stack_status(stack *sta){
printf("stack_size=%d,stack_max_size=%d,stack_is_full=%s,stack_is_empty=%s\n",
sta->size,sta->max_size,stack_is_full(sta) ? "true":"false",stack_is_empty(sta) ? "true":"false");
}