前言:
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 入队列:进行插入操作的一端称为 队尾 出队列:进行删除操作的一端称为 队头
目录
队列的概念及结构
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出 FIFO(First In First Out) 入队列:进行插入操作的一端称为 队尾 出队列:进行删除操作的一端称为 队头
队列的实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数 组头上出数据,效率会比较低。
test.c
#define _CRT_SECURE_NO_WARNINGS 1 #include"Queue.h" void TestQueue() { Queue q; QueueInit(&q); Queuepush(&q, 1); Queuepush(&q, 2); Queuepush(&q, 3); Queuepush(&q, 4); while (!QueueEmpty(&q)) { printf("<==>%d ", QueueFront(&q)); Queuepop(&q); } printf("\n"); QueueDestory(&q); } int main() { TestQueue(); return 0; }
Queue.h
#define _CRT_SECURE_NO_WARNINGS 1 #pragma once #include<stdio.h> #include<assert.h> #include<stdlib.h> #include<stdbool.h> typedef int QDataType; typedef struct QueueNode { struct QueueNode* next; QDataType data; }QNode; typedef struct Queue { QNode* tail; QNode* head; int size; }Queue; //初始化 void QueueInit(Queue* ps); //销毁 void QueueDestory(Queue* ps); //插入 void Queuepush(Queue* ps, QDataType x); //删除 void Queuepop(Queue* ps); //判空 bool QueueEmpty(Queue* ps); //头部展现 QDataType QueueFront(Queue* ps); //尾部展现 QDataType QueueBack(Queue* pq); //数量 QDataType QueueSize(Queue* pq);
Queue.c
#define _CRT_SECURE_NO_WARNINGS 1 #include"Queue.h" //初始化 void QueueInit(Queue* ps) { assert(ps); ps->head = ps->tail = NULL; ps->size = 0; } //销毁 void QueueDestory(Queue* ps) { assert(ps); QNode* cur = ps->head; while (cur) { QNode* del = cur; cur = cur->next; free(del); } ps->head = ps->tail = NULL; } //插入 void Queuepush(Queue* ps, QDataType x) { assert(ps); QNode* newnode = (QNode*)malloc(sizeof(QNode)); if (newnode == NULL) { perror("false"); exit(-1); } else { newnode->data = x; newnode->next = NULL; } if (ps->tail==NULL) { ps->head = ps->tail = newnode; } else { ps->tail->next = newnode; ps->tail = newnode; } ps->size++; } //删除 void Queuepop(Queue* ps) { assert(ps); assert(!QueueEmpty(ps)); if (ps->head->next == NULL) { free(ps->head); ps->head = ps->tail = NULL; } else { QNode* del = ps->head; ps->head = ps->head->next; free(del); del = NULL; } ps->size--; } //判空 bool QueueEmpty(Queue* pq) { assert(pq); return pq->head == NULL && pq->tail == NULL; } //头部展现 QDataType QueueFront(Queue* ps) { assert(ps); return ps->head->data; } //尾部展现 QDataType QueueBack(Queue* pq) { assert(pq); assert(!QueueEmpty(pq)); return pq->tail->data; } //数量 QDataType QueueSize(Queue* pq) { assert(pq); QNode* cur = pq->head; /*int n = 0; while (cur) { ++n; cur = cur->next; } return n;*/ return pq->size; }