C语言实现动态数组堆栈

实现这个的初衷是想要 写树的非递归遍历的

/********************************************************************************
* Copyright(c) 2019-20xx
* All right resered.
*
* @file  	dynaminc_stack.h
* @author 	hongsmallgod
* @version	V1.0.1
* @data		2019-9-10 15:53:29
* @brief	静态数组源文件
********************************************************************************/
#ifndef _DYNAMIC_STACK_H
#define _DYNAMIC_STACK_H
#include <stdbool.h>

typedef int element_type;
typedef struct stack {
    int top; /* 从 0 开始 */
    int size;
    element_type *arr;
    int (*num)(struct stack *); /* 堆栈元素的数量 */
    bool (*pop)(struct stack *, element_type *); 
    bool (*push)(struct stack *, element_type);
    bool (*full)(struct stack *); 
    bool (*empty)(struct stack *); 
} stack;
extern stack *create_stack(int size);
extern void destory_stack(stack *s);
#endif
/********************************************************************************
* Copyright(c) 2019-20xx
* All right resered.
*
* @file  	dynaminc_stack.c
* @author 	hongsmallgod
* @version	V1.0.1
* @data		2019-9-10 15:53:29
* @brief	静态数组头文件
********************************************************************************/
#include <stdlib.h>
#include "dynamic_stack.h"
static bool full(stack *s);
static bool empty(stack *s);
static bool push(stack *s, element_type d);
static bool pop(stack *s, element_type *d);
static int get_stack_num(stack *);

stack *create_stack(int size)
{
    stack *s = (stack *)malloc(sizeof(stack));
    if (NULL == s)
        return NULL;
    s->top = -1;
    s->size = size;

    s->arr = (element_type *)malloc(sizeof(element_type));
    if (NULL == s->arr) {
        free(s);
        return NULL;
    }

    s->num = get_stack_num;
    s->pop = pop;
    s->push = push;
    s->full = full;
    s->empty = empty;
    return s;
}

static int get_stack_num(stack *s)
{
    return s->top + 1;
}
static bool full(stack *s)
{
    if ((s->top + 1) == s->size)
        return true;
    return false;
}
static bool empty(stack *s)
{
    return s->top == -1;
}
static bool push(stack *s, element_type d)
{
    if (full(s))
        return false;
    s->arr[++s->top] = d;

    return true;
}

static bool pop(stack *s, element_type *d)
{
    if (empty(s))
        return 0;
    *d = s->arr[s->top--];
    return 1;
}
void destory_stack(stack *s)
{
    free(s->arr);
    s->arr = NULL;
    free(s);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值