栈和队列

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define DATA_SIZE 2048
#define STACK_SIZE 65536

typedef struct data_s
{
	int len;
	char val[DATA_SIZE];
}data_t;

typedef struct stack_s 
{
	int count;
	data_t data[STACK_SIZE];
}stack_t;

stack_t* stack_create()
{
	stack_t *h = NULL;

	h = (stack_t*)malloc(sizeof(stack_t));
	if(h == NULL)
		return NULL;
	memset(h, 0, sizeof(stack_t));

	return h;
}

int stack_push(stack_t *h, data_t in)
{
	if(h == NULL)
		return -1;

	if(h->count >= STACK_SIZE)
		return -2;

	h->data[h->count].len = in.len;
	memcpy(h->data[h->count].val, in.val, DATA_SIZE);
	h->count = h->count+1;

	return 0;
}

int stack_pop(stack_t *h, data_t *out)
{
	if(h == NULL || out == NULL)
		return -1;

	if(h->count <= 0)
		return -2;

	out->len = h->data[h->count].len;
	memcpy(out->val, h->data[h->count].val, DATA_SIZE);
	h->count = h->count-1;

	return 0;
}

void stack_dump(stack_t *h)
{
	int loop = h->count-1;
	while(loop >= 0)
	{
		fprintf(stdout, "%d: %d-%s\n", loop, h->data[loop].len, h->data[loop].val);
		loop = loop-1;
	}
}

void stack_destroy(stack_t *h)
{
	if(h)
		free(h);
}

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define DATA_SIZE 2048
#define QUEUE_SIZE 65536

typedef struct data_s
{
	int length;
	char value[DATA_SIZE];
}data_t;

typedef struct queue_s 
{
	int head;
	int tail;
	int count;
	data_t data[QUEUE_SIZE];
}queue_t;

queue_t* queue_create()
{
	queue_t *h = NULL;

	h = (queue_t*)malloc(sizeof(queue_t));
	if(h == NULL)
		return NULL;
	memset(h, 0, sizeof(queue_t));

	return h;
}

int queue_add(queue_t *h, data_t in)
{
	if(h == NULL)
		return -1;

	if(h->count >= QUEUE_SIZE)
		return -2;

	h->data[h->tail].length = in.length;
	memcpy(h->data[h->tail].value, in.value, DATA_SIZE);
	h->tail = (h->tail+1)%QUEUE_SIZE;
	h->count = h->count+1;

	return 0;
}

int queue_del(queue_t *h, data_t *out)
{
	if(h == NULL || out == NULL)
		return -1;

	if(h->count <= 0)
		return -2;

	out->length = h->data[h->head].length;
	memcpy(out->value, h->data[h->head].value, DATA_SIZE);
	h->head = (h->head+1)%QUEUE_SIZE;
	h->count = h->count-1;

	return 0;
}

void queue_dump(queue_t *h)
{
	int loop = h->head;
	if(h->count == QUEUE_SIZE)
	{
		fprintf(stdout, "%d: %d-%s\n", loop, h->data[loop].length, h->data[loop].value);
		loop = (loop+1)%QUEUE_SIZE;
	}
	while(loop != h->tail)
	{
		fprintf(stdout, "%d: %d-%s\n", loop, h->data[loop].length, h->data[loop].value);
		loop = (loop+1)%QUEUE_SIZE;
	}
}

void queue_destory(queue_t *h)
{
	if(h)
		free(h);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值