[数据结构]6. 队列-Queue

队列-Queue

  • [1. 介绍](#1. 介绍)
  • [2. 队列实现](#2. 队列实现)
    • [2.1 基于链表的实现](#2.1 基于链表的实现)
    • [2.2 基于数组的实现](#2.2 基于数组的实现)
  • [3. 队列操作](#3. 队列操作)

1. 介绍

队列(queue) 是一种遵循先入先出规则的线性数据结构。将队列头部称为"队首",尾部称为"队尾",将把元素加入队尾的操作称为"入队",删除队首元素的操作称为"出队"。

2. 队列实现

2.1 基于链表的实现


2.2 基于数组的实现


3. 队列操作

Create

c 复制代码
typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;

typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;

Initialize

c 复制代码
void QueueInit(Queue* pq) {
	assert(pq);
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}

Destory

c 复制代码
void QueueDestory(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;
}

Push

c 复制代码
void QueuePush(Queue* pq, QDataType x) {
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL) {
		perror("malloc fail\n");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->ptail == NULL) {
		assert(pq->phead == NULL);
		pq->phead = pq->ptail = newnode;
	}
	else {
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}

Pop

c 复制代码
void QueuePop(Queue* pq) {
	assert(pq);
	assert(!QueueEmpty(pq));
	// one node
	if (pq->phead->next == NULL) {
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	// more node
	else {
		QNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	pq->size--;
}

Front

c 复制代码
QDataType QueueFront(Queue* pq) {
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->phead->data;
}

Back

c 复制代码
QDataType QueueBack(Queue* pq) {
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->ptail->data;
}

Size

c 复制代码
int QueueSize(Queue* pq) {
	assert(pq);
	return pq->size;
}

Empty

c 复制代码
bool QueueEmpty(Queue* pq) {
	assert(pq);
	//return pq->phead == NULL && pq->ptail == NULL;
	return pq->size == 0;
}
相关推荐
Star在努力几秒前
15-C语言:第15~16天笔记
c语言·笔记·算法
LZQqqqqo2 分钟前
C# 接口(interface 定义接口的关键字)
java·开发语言·c#
CoovallyAIHub6 分钟前
工业质检新突破!YOLO-pdd多尺度PCB缺陷检测算法实现99%高精度
深度学习·算法·计算机视觉
gb42152876 分钟前
负载均衡算法中的加权随机算法
windows·算法·负载均衡
寒水馨10 分钟前
Java 9 新特性解析
java·开发语言·新特性·java9·jdk9
拓端研究室31 分钟前
专题:2025医药生物行业趋势与投融资研究报告|附90+份报告PDF、原数据表汇总下载
android·开发语言·kotlin
RXXW_Dor1 小时前
数据结构之线性表
数据结构
xdlka1 小时前
C++初学者4——标准数据类型
开发语言·c++·算法
go54631584651 小时前
大规模矩阵构建与高级算法应用
线性代数·算法·矩阵
向左转, 向右走ˉ2 小时前
为什么分类任务偏爱交叉熵?MSE 为何折戟?
人工智能·深度学习·算法·机器学习·分类·数据挖掘