栈的编写
其实是一个数组+ 记录栈空间元素个数的qty
栈的头文件stack.h
#ifndef __STACK_H_
#define __STACK_H_
#include<stdio.h>
typedef struct {
int buf[SIZE];
int qty;
} stack_t;
void stack_init(stack_t * );
void stack_deinit(stack_t *);
int stack_size (const stack_t *);
int stack_empty(const stack_t *);
int stack_full(const stack_t *);
int pop(stack_t *, int *);
int push(stack_t *, int );
int top (const stack_t *, int *);
#endif
栈的函数实现,包括pop top push 判定是否为空,是否为满等
stack.c
#include"stack.h"
void stack_init(stack_t * p_stack)
{
p_stack->qty = 0;
}
void stack_deinit(stack_t *p_stack)
{
p_stack->qty = 0;
}
int stack_size (const stack_t *p_stack)
{
return p_stack->qty;
}
int stack_empty(const stack_t *p_stack)
{
return !p_stack->qty;
}
int stack_full(const stack_t *p_stack)
{
return p_stack->qty >= SIZE;
}
int pop(stack_t *p_stack, int *p_val)
{
if (stack_empty(p_stack))
return 0;
*p_val = p_stack->buf[p_stack->qty -1];
p_stack->qty = p_stack->qty -1;
return 1;
}
int push(stack_t *p_stack, int val)
{
if (stack_full(p_stack))
return 0;
p_stack->buf[p_stack->qty] = val;
p_stack->qty = p_stack->qty + 1;
return 1;
}
int top (const stack_t *p_stack, int *p_val)
{
if(stack_empty(p_stack))
return 0;
*p_val = p_stack->buf[p_stack->qty -1];
return 1;
}
栈的主函数
stack_main.c
#include<stdio.h>
#include"stack.h"
int main()
{
stack_t stk = {0};
int val = 0;
stack_init(&stk);
printf("stack empty result is %d\n",stack_empty(&stk));
printf("stack full result is %d\n",stack_full(&stk));
printf("stack size is %d\n",stack_size(&stk));
push(&stk,10);
push(&stk,100);
push(&stk,20);
push(&stk,35);
push(&stk,50);
printf(" empty result is %d\n",stack_empty(&stk));
printf(" full result is %d\n",stack_full(&stk));
printf("stack size is %d\n",stack_size(&stk));
top(&stk,&val);
printf("stack top number is %d\n",val);
while (!stack_empty(&stk))
{
pop(&stk,&val);
printf("%d ",val);
}
printf("\n");
}
编译 gcc -DSIZE=5 stack_main.c stack.c