[数据结构]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;
}
相关推荐
superlls几秒前
(数据结构)哈希碰撞:线性探测法 vs 拉链法
算法·哈希算法·散列表
midsummer_woo5 分钟前
#数据结构----2.1线性表
数据结构
ShineWinsu5 分钟前
对于单链表相关经典算法题:206. 反转链表及876. 链表的中间结点的解析
java·c语言·数据结构·学习·算法·链表·力扣
再睡一夏就好17 分钟前
【C++闯关笔记】STL:list 的学习和使用
c语言·数据结构·c++·笔记·算法·学习笔记
要做朋鱼燕20 分钟前
【C++】 list 容器模拟实现解析
开发语言·c++·笔记·职场和发展·list
Ka1Yan26 分钟前
MySQL索引优化
开发语言·数据结构·数据库·mysql·算法
MediaTea41 分钟前
Python 内置函数:pow()
开发语言·python
AndrewHZ1 小时前
【图像处理基石】图像预处理方面有哪些经典的算法?
图像处理·python·opencv·算法·计算机视觉·cv·图像预处理
阿维的博客日记1 小时前
LeetCode 209 - 长度最小的子数组算法详解
数据结构·算法·leetcode
上位机付工1 小时前
上位机通信速度有多快?
开发语言·c#·上位机·plc