[数据结构]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;
}
相关推荐
AndrewHZ1 分钟前
【复杂网络分析】什么是图神经网络?
人工智能·深度学习·神经网络·算法·图神经网络·复杂网络
沐知全栈开发3 分钟前
ASP 实例:深入浅出地了解ASP技术
开发语言
Swizard8 分钟前
拒绝“狗熊掰棒子”!用 EWC (Elastic Weight Consolidation) 彻底终结 AI 的灾难性遗忘
python·算法·ai·训练
待╮續11 分钟前
JVMS (JDK Version Manager) 使用教程
java·开发语言
龘龍龙19 分钟前
Python基础学习(四)
开发语言·python·学习
U-52184F6924 分钟前
C++ 实战:构建通用的层次化数据模型 (Hierarchical Data Model)
开发语言·c++
火一线30 分钟前
【C#知识点详解】基类、抽象类、接口类型变量与子类实例的归纳总结
开发语言·c#
Trouvaille ~35 分钟前
【C++篇】把混沌映射成秩序:哈希表的底层哲学与实现之道
数据结构·c++·stl·哈希算法·散列表·面向对象·基础入门
李慕婉学姐36 分钟前
【开题答辩过程】以《基于PHP的动漫社区的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
开发语言·mysql·php
Yeats_Liao1 小时前
MindSpore开发之路(四):核心数据结构Tensor
数据结构·人工智能·机器学习