#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <stdbool.h> typedef struct QueueNode { struct QueueNode* next; int data; }QueueNode; //将来的队列 typedef struct Queue { QueueNode *head; QueueNode *tail; }Queue; //两个指针,放在结构体里用,方便一点,不用传二级指针 void QueueInit(Queue* like); void QueueTest(); void QueueDestroy(Queue *like); void QueuePush(Queue* like,int data); void QueuePop(Queue* like); int QueueFront(Queue* like); int QueueBack(Queue* like); int QueueSize(Queue* like); bool QueueEmpty(Queue* like); int main() { QueueTest(); return 0; } #include "queue.h" void QueueTest() { //创建Queue类型结构体,里面放了两个Queuenode型的指针 Queue like; QueueInit(&like); QueuePush(&like, 1); QueuePush(&like, 2); QueuePush(&like, 3); QueuePush(&like, 4); QueuePush(&like, 5); } void QueueInit(Queue* like) { assert(like); //断言,如果like为空,中止运行并报错 like->head = NULL; like->tail = NULL; //置空 } void QueueDestroy(Queue* like) { assert(like); QueueNode* cur = like->head; //用cur存下头节点指针 while (cur != NULL)//这里不要让cur!=like->tail,因为删到最后,cur==like->tail //的时候,最后一个删不掉 { like->head = like->head->next; free(cur); cur = like->head; //先存下一个数据,释放当前,再指向下一个 } like->head = like->tail = NULL; //释放完后,全部置空,避免变成野指针 } void QueuePush(Queue* like, int data) { assert(like); QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode)); newnode->data = data; newnode->next = NULL; //创建新节点并填充数据 if (like->head == NULL) { //如果头为空,头尾指针都指向新节点 like->head = like->tail = newnode; } else { //正常操作插入 like->tail->next = newnode; like->tail = newnode; } void QueuePop(Queue* like) { assert(like); assert(!QueueEmpty(like)); //如果like->head为空,!1=0,中止 QueueNode* con = like->head->next; free(like->head); like->head = con; if (like->head == NULL) { //此处是为了避免野指针的出现,后续如果数据删完,要求尾数据,没有 //这个if语句,那就会报错,因为head为NULL,但对tail没有操作 like->tail == NULL; } } //求队列的头数据 int QueueFront(Queue* like) { assert(like); assert(!QueueEmpty(like)); return like->head->data; } //求队列的尾数据 int QueueBack(Queue* like) { assert(like); assert(!QueueEmpty(like)); return like->tail->data; } //计算队列长度 int QueueSize(Queue* like) { assert(like); int n = 0; QueueNode* cur = like->head; while (cur) { n++; cur = cur->next; } return n; } //判断like->head是否为空 bool QueueEmpty(Queue* like) { assert(like); return like->head == NULL; }