数据结构基础(3)-->队列

queue.h
#ifndef	QUEUE_H
#define	QUEUE_H		1
#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define	QUEUE_NODE_MAX		1024

struct qnode
{
	char		name[32];
	int		num;
	struct	qnode	*next;
};
struct queue
{
	int		queuesize;
	struct	qnode	*head;
	struct	qnode	*tail;
};

int initqueue(struct queue **head);
void destroyqueue(struct queue **head);
void clearqueue(struct queue *head);
int queueempty(const struct queue *head);
int queuelength(const struct queue *head);
int queueinsert(struct queue *head, struct qnode *new);
struct qnode *queuedelete(struct queue *head);
void printqnode(const struct qnode *node);
int printqhead(const struct queue *head);

#endif /* QUEUE_H */
queue.c
#include <queue.h>

int initqueue(struct queue **head)
{
	*head = (struct queue *)malloc(sizeof(struct queue));
	if(!*head) {
		return -1;
	}
	(*head)->queuesize = 0;
	memset(*head, 0, sizeof(struct queue));
	(*head)->head = (struct qnode *)malloc(sizeof(struct qnode));
	(*head)->tail = (struct qnode *)malloc(sizeof(struct qnode));
	if(!(*head)->head || (!(*head)->tail)) {
		free((*head)->head);
		free((*head)->tail);
		free(*head);
		*head = NULL;
		return -1;
	}
	strcpy((*head)->head->name, "head");
	(*head)->head->num = 0;
	(*head)->head->next = (*head)->tail;
	strcpy((*head)->tail->name, "tail");
	(*head)->tail->num = 0;
	(*head)->tail->next = (*head)->head;
	return 0;
}
void destroyqueue(struct queue **head)
{
	clearqueue(*head);
	free(*head);
	*head = NULL;
}
void clearqueue(struct queue *head)
{
	struct	qnode	*node;
	while(head->head->next != head->tail) {
		node = head->head->next->next;
		free(head->head->next);
		head->head->next = node;
	}
}
int queueempty(const struct queue *head)
{
	return head->head->next == head->tail;
}
int queuelength(const struct queue *head)
{
	return head->queuesize;
}
int queueinsert(struct queue *head, struct qnode *new)
{
	if(QUEUE_NODE_MAX == head->queuesize) {
		return -1;
	}
	++(head->queuesize);
	new->next = head->tail;
	head->tail->next->next = new;
	head->tail->next = new;
	return 0;
}
struct qnode *queuedelete(struct queue *head)
{
	if(queueempty(head)) {
		return NULL;
	}
	--(head->queuesize);
	struct qnode *node;
	node = head->head->next;
	head->head->next = node->next;
	node->next = NULL;
	if(queueempty(head)) {
		head->tail->next = head->head;
	}
	return node;
}
void printqnode(const struct qnode *node)
{
	if(node) {
		printf("name=%10s, num=%3d...\n", node->name, node->num);
	} else {
		printf("is null...\n");
	}
}
int printqhead(const struct queue *head)
{
	struct qnode *n = head->head;
	do {
		printqnode(n);
		n = n->next;
	}while(n!=head->tail);
	printqnode(n);
	printf("printqhead end...\n");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值