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;
}