队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头。
上图可以看出队列数据满足一个规则:先进先出。当然这也是相对于队列里面的数据的规则。
基于这一特点我们也来实现一下队列的代码,但是现在有一个问题:用那种结构去写呢?
在这里哦我们发现这个结构如果用数组去写的话,那每次的插入数据都需要进行找尾操作,虽然我们可以通过指针的方法,没插入数据尾指针就往后退一步,首指针指向第一数据,但是当我们出数据的时候我们保存指针数据的方式,和再次移动头指针的操作会有些麻烦。所以这里用链表的方法会更好。
.h文件
#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int QDatatype;
typedef struct QueueNode {
QDatatype val;
struct QueueNode* next;
}QNode;
//创建两个指针开来方便出数据和进数据
typedef struct Queue {
QNode* phead;
QNode* ptail;
int size;
}Queue;
//将其放入一个结构体,方便传参
//初始化
void QueueInit(Queue* pq);
//销毁
void QueueDestroy(Queue* pq);
//入队列
void QueuePush(Queue* pq,QDatatype x);
//出队列
void QueuePop(Queue* pq);
//取值
QDatatype QueueFront(Queue* pq);
QDatatype QueueBack(Queue* pq);
//判断是否为空
bool QueueEmpty(Queue* pq);
//计算节点个数
int QueueSize(Queue* pq);
.c文件
#include"Queue.h"
//初始化
void QueueInit(Queue* pq) {
assert(pq);
pq->phead = NULL;
pq->ptail = NULL;
pq->size = 0;
}
//销毁
void QueueDestroy(Queue* pq) {
assert(pq);
QNode* cur = pq->phead;
while (cur) {
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->phead = NULL;
pq->ptail = NULL;
pq->size = 0;
}
//入队列
void QueuePush(Queue* pq,QDatatype x) {
assert(pq);
QNode* newNode = (QNode*)malloc(sizeof(QNode));
if (newNode == NULL) {
perror("malloc fail !");
return;
}
newNode->val = x;
newNode->next = NULL;
if (pq->ptail!=NULL) {
pq->ptail->next = newNode;
pq->ptail = newNode;
}
else {
pq->ptail = pq->phead = newNode;
}
pq->size++;
}
//出队列
void QueuePop(Queue* pq) {
assert(pq);
//空链表
assert(pq->phead);
//一个节点或多个节点
if (pq->phead->next == NULL) {
free(pq->phead);
pq->phead = pq->ptail = NULL;
}
else {
QNode* cur = pq->phead->next;
free(pq->phead);
pq->phead = cur;
}
pq->size--;
}
//取值
//取队头
QDatatype QueueFront(Queue* pq) {
assert(pq&&pq->phead!=NULL);
return pq->phead->val;
}
//取队尾
QDatatype QueueBack(Queue* pq) {
assert(pq && pq->phead != NULL);
return pq->ptail->val;
}
//判断是否为空
bool QueueEmpty(Queue* pq) {
assert(pq);
return pq->size == 0;
}
//计算节点个数
int QueueSize(Queue* pq) {
assert(pq);
return pq->size;
}
当然大家不需要写的一样,只要运行逻辑差不多即可。可以适当发挥,写法是很多的。
