[数据结构]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;
}
相关推荐
秃头小白菜10 分钟前
Python之三大基本库——Matplotlib
开发语言·python·matplotlib
Hygge-star16 分钟前
【算法】定长滑动窗口5.20
java·数据结构·算法·学习方法·代码规范
好易学·数据结构16 分钟前
可视化图解算法42:寻找峰值
算法
June`16 分钟前
专题五:floodfill算法(图像渲染深度优先遍历解析与实现)
c++·算法·leetcode·深度优先·剪枝·floodfill
流星白龙17 分钟前
【C++算法】70.队列+宽搜_N 叉树的层序遍历
开发语言·c++·算法
一定要AK19 分钟前
萌新联赛第(三)场
数据结构·c++·算法
空雲.19 分钟前
ABC 355
算法
流星白龙22 分钟前
【C++算法】69.栈_验证栈序列
开发语言·c++·算法
你好我是咯咯咯23 分钟前
代码随想录算法训练营Day59
算法
Luis Li 的猫猫35 分钟前
MATLAB跳动的爱心
开发语言·算法·matlab