[数据结构]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;
}
相关推荐
best_virtuoso13 分钟前
PostgreSQL 常见数组操作函数语法、功能
java·数据结构·postgresql
yudiandian201413 分钟前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
要加油哦~19 分钟前
JS | 知识点总结 - 原型链
开发语言·javascript·原型模式
伏小白白白35 分钟前
【论文精度-2】求解车辆路径问题的神经组合优化算法:综合展望(Yubin Xiao,2025)
人工智能·算法·机器学习
鄃鳕36 分钟前
python迭代器解包【python】
开发语言·python
new coder37 分钟前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
驰羽43 分钟前
[GO]GORM 常用 Tag 速查手册
开发语言·后端·golang
Narcissiffo1 小时前
【C语言】str系列函数
c语言·开发语言
workflower1 小时前
软件工程与计算机科学的关系
开发语言·软件工程·团队开发·需求分析·个人开发·结对编程
ajsbxi1 小时前
【Java 基础】核心知识点梳理
java·开发语言·笔记