2020-10-22

栈的编写
其实是一个数组+ 记录栈空间元素个数的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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值