队列,是先进先出(FIFO)的线性表。在具体应用中通常用链表或者数组来实现。队列只允许在后端(称为rear)进行插入操作,在前端(称为front)进行删除操作。
queue.h
- #ifndef _QUEUE_H
- #define _QUEUE_H
- #define Type int
- #ifdef _MSC_VER
- #define bool int
- #define true 1
- #define false 0
- #else
- #include <stdbool.h>
- #include <stdint.h>
- #endif
- struct queue;
- struct queue *init_queue();
- void destory_queue(struct queue *q);
- void clear_queue(struct queue *q);
- bool en_queue(struct queue *q, Type data);
- bool de_queue(struct queue *q);
- Type gethead(struct queue *q);
- bool queue_empty(struct queue *q);
- int queue_size(struct queue *q);
- void print_queue(struct queue *q);
- #endif
queue.c
- #include "queue.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- struct queue_node {
- Type data;
- struct queue_node *next;
- };
- struct queue {
- struct queue_node *front;
- struct queue_node *rear;
- };
- struct queue *init_queue()
- {
- struct queue *q = (struct queue *)malloc(sizeof(struct queue));
- if (q == NULL)
- return NULL;
- q->front = q->rear = (struct queue_node *)malloc(sizeof(struct queue_node));
- if (q->front == NULL)
- return NULL;
- q->front->next = NULL;
- return q;
- }
- void destory_queue(struct queue *q)
- {
- assert(q != NULL);
- while (q->front != NULL) {/*also free head node*/
- q->rear = q->front->next;
- free (q->front);
- q->front = q->rear;
- }
- free(q);
- q = NULL;
- }
- void clear_queue(struct queue *q)
- {
- assert(q != NULL);
- struct queue_node *h, *p;
- h = q->front->next;
- q->rear = q->front;
- q->front->next = NULL;
- while (h != NULL) {
- p = h;
- h = h->next;
- free(p);
- }
- }
- bool en_queue(struct queue *q, Type data)
- {
- assert(q != NULL);
- struct queue_node *p = (struct queue_node *)malloc(sizeof(struct queue_node));
- if (p == NULL)
- return false;
- p->data = data;
- p->next = NULL;
- q->rear->next = p;
- q->rear = p;
- return true;
- }
- bool de_queue(struct queue *q)
- {
- assert(q != NULL);
- if (q->front == q->rear)
- return false;
- struct queue_node *p = q->front->next;
- q->front->next = p->next;
- if (q->rear == p)
- q->rear = q->front;/*null*/
- free(p);
- return true;
- }
- bool queue_empty(struct queue *q)
- {
- assert(q != NULL);
- if (q->front->next == NULL)
- return true;
- else
- return false;
- }
- int queue_size(struct queue *q)
- {
- struct queue_node *p = q->front;
- int i = 0;
- while (p != q->rear) {
- i++;
- p = p->next;
- }
- return i;
- }
- Type gethead(struct queue *q)
- {
- assert(q != NULL);
- if (q->front != q->rear)
- return q->front->next->data;
- else
- return 0;
- }
- void print_queue(struct queue *q)
- {
- assert(q != NULL);
- struct queue_node *p = q->front;
- while (p->next != NULL) {
- p = p->next;
- printf("%d ", p->data);
- }
- }
主函数
- #include <stdio.h>
- #include "queue.h"
- int main()
- {
- struct queue *q = init_queue();
- en_queue(q, 2);
- en_queue(q, 1);
- en_queue(q, 3);
- en_queue(q, 5);
- de_queue(q);
- print_queue(q);
- destory_queue(q);
- return 0;
- }