顺序栈
定义数据结构:
typedef void (stack_op_t)(const void *);
//抽象栈数据类型
typedef struct stack_t{
void *stack;//数据
int size;//栈中数据类型
int top;//栈顶指针
int max;//栈大小
}STACK;
//初始化
STACK *stack_creat(int size, int max);
//入栈
int stack_push(STACK *handle, void *data);
//出栈
void *stack_pop(STACK *handle);
//判断满栈
int stack_is_full(STACK *handle);
//判断空栈
int stack_is_empty(STACK *handle);
//遍历
void stack_travel(STACK *handle, stack_op_t *op);
//销毁
void stack_destroy(STACK **handle);
//清空
void stack_clean(STACK *handle);
//存储
void stack_store(STACK *handle, const char *path);
//加载
STACK *stack_load(const char *path);
// init creat
STACK *stack_creat(int size, int max)
{
STACK *handle = NULL;
handle = (STACK *)malloc(sizeof(STACK));
ERRP(NULL == handle, handle malloc, goto ERR1);
handle->size = size;
handle->max = max;
handle->top = 0;
handle->stack = (void *)malloc(size * max);
ERRP(NULL == handle->stack, handle->stack malloc, goto ERR2);
return handle;
ERR2:
free(handle);
ERR1:
return NULL;
}
**//push **
int stack_push(STACK *handle, void *data)
{
if (stack_is_full(handle))
{
return 0;
}
else
{
memmove(handle->stack + handle->size * handle->top, data, handle->size);
handle->top++;
}
return 1;
}
// pop
void *stack_pop(STACK *handle)
{
if (stack_is_empty(handle))
{
return NULL;
}
handle->top--;
return handle->stack + handle->size * handle->top;
}
//is_full ?
int stack_is_full(STACK *handle)
{
if (handle->top == handle->max)
{
return 1;
}
else
{
return 0;
}
}
//is_empty ?
int stack_is_empty(STACK *handle)
{
if (handle->top == 0)
{
return 1;
}
else
{
return 0;
}
}
//traval
void stack_travel(STACK *handle, stack_op_t *op)
{
if (handle->stack == NULL)
{
return;
}
int i;
for (i = 0; i < handle->top; i++)
{
op(handle->stack + i * handle->size);
}
}
//destroy
void stack_destroy(STACK **handle)
{
free((*handle)->stack);
(*handle)->stack = NULL;
free(*handle);
*handle = NULL;
}
//clean
void stack_clean(STACK *handle)
{
while (handle->top)
{
stack_pop(handle);
}
}
**//fileio **
void stack_store(STACK *handle, const char *path)
{
FILE *fp = NULL;
fp = fopen(path, "w");
ERRP(NULL == fp, fopen, goto ERR1);
if (fwrite(handle, sizeof(*handle), 1, fp) != 1)
{
perror("fwrite");
goto ERR2;
}
if (fwrite(handle->stack, handle->size, handle->top, fp) != handle->top)
{
perror("fwrite");
goto ERR2;
}
fclose(fp);
return;
ERR2:
fclose(fp);
ERR1:
return;
}
// 加载
STACK *stack_load(const char *path)
{
FILE *fp = NULL;
fp = fopen(path, "r");
ERRP(NULL == fp, fopen, goto ERR1);
STACK *handle = NULL;
handle = (STACK *)malloc(sizeof(STACK));
ERRP(NULL == handle, handle malloc, goto ERR2);
if (fread(handle, sizeof(*handle), 1, fp) != 1)
{
perror("fread");
goto ERR3;
}
handle->stack = (void *)malloc(handle->size * handle->top);
ERRP(handle->stack == NULL, handle->stack malloc, goto ERR3);
if (fread(handle->stack, handle->size, handle->top, fp) != handle->top)
{
perror("fread");
free(handle->stack);
goto ERR3;
}
fclose(fp);
return handle;
ERR3:
free(handle);
ERR2:
fclose(fp);
ERR1:
return NULL;
}