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

来源:互联网 发布:购物车保存到数据库 编辑:程序博客网 时间:2024/06/08 01:13
queue.h
#ifndefQUEUE_H#defineQUEUE_H1#include <stdio.h>#include <string.h>#include <malloc.h>#defineQUEUE_NODE_MAX1024struct qnode{charname[32];intnum;structqnode*next;};struct queue{intqueuesize;structqnode*head;structqnode*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){structqnode*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;}