数据结构--队列

1.队列的概念与结构

只允许在⼀端进⾏插⼊数据操作,在另⼀端进⾏删除数据操作的特殊线性表,队列具有先进先出

⼊队列:进⾏插⼊操作的⼀端称为队尾

出队列:进⾏删除操作的⼀端称为队头

队列也可以数组和链表的结构实现,使⽤链表的结构实现更优⼀些,因为如果使⽤数组的结构,出队 列在数组头上出数据,效率会⽐较低。

2.队列的实现

a.队列节点的结构

cpp 复制代码
typedef struct QueueNode
{
int data;
struct QueueNode*next;
}QueueNode;

b.队列的结构

cpp 复制代码
typedef struct Queue
{
QueueNode*phead;
QueueNode*ptail;
}Queue;

c.初始化

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

d.入队--队尾

cpp 复制代码
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
QueueNode*newnode=(QueueNode*)malloc(sizeof(QueueNode));
if(newnode==NULL)
{
perror("malloc fail");
exit(1);
}
newnode->data=x;
newnode->next=NULL;
if(pq->phead==pq->ptail)
{
pq->phead=pq->ptail=newnode;
}
else
{
pq->ptail->next=newnode;
pq->ptail=pq->ptail->next;
}
}

e.队列判空

cpp 复制代码
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->phead==NULL;
}

f.出队--队头

cpp 复制代码
void QueuePop(Queue* pq)
{
assert(!(QueueEmpty(&pq));
if(pq->phead==pq->ptail)
{
free(pq-->phead);
pq->phead=pq->ptail=NULL;
}
else
{
QueueNode*next=pq->phead->next;
free(pq->phead);
pq->phead=NULL;
pq->phead=next;
}
}

g.取队头数据

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

h.取队尾数据

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

i.队列有效元素个数

cpp 复制代码
int QueueSize(Queue* pq)
{
 assert(&pq);
int size;
 QueueNode*pcur=pq->phead;
 while(pcur)
 {
size++;
pq->phead=pq->phead->next;
 }
return size;
}

j.销毁队列

cpp 复制代码
void QueueDestroy(Queue* pq)
{
assert(&pq);
QueueNode*pcur=pq->phead;
while(pcur)
{
QueueNode*next=pcur->next;
free(pcur);
pcur=next;
}
pq->phead=pq->ptail=NULL;
}
相关推荐
袋鼠云数栈5 小时前
集团数字化统战实战:统一数据门户与全业态监管体系构建
大数据·数据结构·人工智能·多模态
小月球~6 小时前
天梯赛 · 并查集
数据结构·算法
仍然.6 小时前
算法题目---模拟
java·javascript·算法
三道渊7 小时前
C语言:文件I/O
c语言·开发语言·数据结构·c++
kali-Myon8 小时前
CTFshow-Pwn142-Off-by-One(堆块重叠)
c语言·数据结构·安全·gdb·pwn·ctf·
潇冉沐晴8 小时前
DP——背包DP
算法·背包dp
GIOTTO情9 小时前
2026 世界互联网大会亚太峰会|AI 时代媒介投放的技术实战与算法优化
人工智能·算法
逆境不可逃9 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
计算机安禾9 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
副露のmagic9 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法