队列的实现0

本节介绍队列的定义及基本操作。

1)队列定义:

typedef struct __queue queue;
typedef struct __node  node;

struct __queue
{
	struct __node *front;
	struct __node *rear;

	int size;
};

struct __node
{
	struct __node *pre;
	struct __node *next;
	void *data;
};

2)基本操作:

queue *create(void *data)
{
	queue *q = NULL;
	node  *p = NULL;	
	
	q = (queue *)malloc(sizeof(struct __queue));

	if (q == NULL)
	{
		perror("create queue node failed!\n");
		return NULL;
	}

	q->front = NULL;
	q->rear  = NULL;

	q->size = 0;

	return q;
}

int en_queue(queue *q, void *data)
{
	node *p;

	if (q == NULL)
	{
		perror("invalid queue!\n");
		return -1;
	}
	
	if (q->size > MAX_NODE)
	{
		perror("beyond max queue size!\n");
		return -1;
	}

	p = (node *)malloc(sizeof(struct __node));
	if (p == NULL)
	{
		perror("alloc new node failed!\n");
		return -1;
	}
		
	p->data = malloc(sizeof(int));
	*(int *)(p->data) = *(int *)data;

	if (q->rear == NULL && q->front == NULL)
	{
		//add first node here;
		q->front = p;
		q->front->pre = NULL;
		q->front->next = NULL;

		q->rear = p;
		q->rear->pre = NULL;
		q->rear->next = NULL;
	}
	else
	{
		q->rear->next = p;
		p->pre  = q->rear;
		p->next = NULL;	
		q->rear = p;
	}

	(q->size) ++;

	return 0;
}

int de_queue(queue *q, void *data)
{
	node *p = NULL;
	
	if (q == NULL || q->size <= 0)
	{
		perror("invalid queue!\n");
		return -1;
	}

	p = q->front;
	*(int *)data = *(int *)(p->data);
	
	if (p->next != NULL)
	{
		q->front = p->next;
		q->front->pre = NULL;
	}

	(q->size) --;

	free(p->data);
	free(p);

	return 0;
}

int destory_queue(queue *q)
{
	node *p = NULL;
	
	if (q == NULL)
		return 0;

	for (p = q->front; p != NULL; p = p->next)
	{
		free(p->data);
		free(p);
	}

	free(q);

	return 0;
}

3)打印所有元素:

int dump_queue(queue *q)
{
	node *p = NULL;
	int count = 0;
	
	if (q == NULL)
	{
		perror("invalid queue!\n");	
		return -1;
	}
	
	for(p = q->front; p != NULL; p = p->next, count ++)
	{
		if (count != 0 && count % LINE_NUM == 0)
			printf("\n");		

		printf("%d\t", *(int *)(p->data));
	}

	printf("\n");

	return 0;
}

下一节将介绍测试代码及说明。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值