c 语言栈,C 语言栈简单实现

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");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值