一队列的简单理解
1.队列的概念和结构
队列(Queue)是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。
队列具有先进先出FIFO(First In First Out)
入队列:进行插入操作的一端称为队尾
出队列:进行删除操作的一端称为队头
二、队列的实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。
数组实现:使用数组来存储队列元素,但需要两个指针(或索引)来分别指示队首和队尾的位置。这种实现方式需要处理“假溢出”的问题,即当队列尾部的元素被移除后,队列的前部还有空间可以利用,但此时因为尾部索引已经到达数组末尾,所以无法再向队列中添加新元素。
链表实现:使用链表来存储队列元素,队首和队尾分别指向链表的头结点和尾结点。这种实现方式不需要担心“假溢出”的问题,因为链表是动态分配的。
1、Queue.h的实现
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType val;
}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);
//队列中的数据个数
int QueueSize(Queue* pq);
//判空
bool QueueEmpty(Queue* pq);
为了不使用二级指针,我们定义一个结构体来储存指向头节点和尾节点的指针,避免指针的过多引用导致出错。
2、Queue.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 = 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->next = NULL;
newnode->val = x;
if (pq->ptail == NULL)
{
pq->phead = pq->ptail = newnode;
}
else
{
pq->ptail->next = newnode;
pq->ptail = newnode;
}
pq->size++;
}
// 队头删除
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->size != 0);
// 一个节点
if (pq->phead->next == NULL)
{
free(pq->phead);
pq->phead = pq->ptail = NULL;
}
else // 多个节点
{
QNode* next = pq->phead->next;
free(pq->phead);
pq->phead = next;
}
pq->size--;
}
//取出头节点
QDataType QueueFront(Queue* pq)
{
assert(pq);
assert(pq->phead);
return pq->phead->val;
}
//取出尾节点
QDataType QueueBack(Queue* pq)
{
assert(pq);
assert(pq->ptail);
return pq->ptail->val;
}
//数据个数
int QueueSize(Queue* pq)
{
assert(pq);
return pq->size;
}
//判空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->size==0;
}
3、test.c的实现
#include"Queue.h"
int main()
{
Queue pst;
//初始化
QueueInit(&pst);
// 队尾插入
QueuePush(&pst, 1);
QueuePush(&pst, 2);
QueuePush(&pst, 3);
QueuePush(&pst, 4);
QueuePush(&pst, 5);
//队头取出
while (!QueueEmpty(&pst))
{
printf("%d ", QueueFront(&pst));
QueuePop(&pst);
}
printf("\n");
//队列的销毁
QueueDestroy(&pst);
return 0;
}