数据结构——队列

队列:只允许在⼀端进行插⼊数据操作,在另⼀端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)

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

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

动态模拟队列(链表)

头文件 queue.h

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>

typedef int QDataType;
typedef struct QueueNode
{
	QDataType data;
	struct QueueNode* next;
}QNode;//队列节点
typedef struct Queue
{
	QNode* phead;
	QNode* ptail;//队头队尾指针
}Queue;//队列

//初始化
void QInit(Queue* pq);

//销毁队列
void QDestroy(Queue* pq);

//队尾入队列
void QPush(Queue* pq, QDataType x);

//队头出队列
void QPop(Queue* pq);

//返回队头元素
QDataType QFront(Queue* pq);

//返回队尾元素
QDataType QBack(Queue* pq);

//队列元素个数
int QSize(Queue* pq);

//队列是否为空
bool QEmpty(Queue* pq);

源文件 queue.c 

#include"queue.h"

//初始化
void QInit(Queue* pq)
{
	assert(pq);
	pq->phead = pq->ptail = NULL;
}

//销毁队列
void QDestroy(Queue* pq)
{
	assert(pq);
	QNode* pcur = pq->phead;
	while (pcur)
	{
		QNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	pq->phead = pq->ptail = NULL;
}

//队列是否为空
bool QEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead == NULL;
}

//队尾入队列
void QPush(Queue* pq, QDataType x)
{
	assert(pq);
	//申请节点
	QNode* node = (QNode*)malloc(sizeof(QNode));
	if (node == NULL)
	{
		perror("malloc");
		exit(1);
	}
	node->data = x;
	node->next = NULL;

	if (pq->phead == NULL)
	{
		pq->phead = pq->ptail = node;
	}
	else
	{
		pq->ptail->next = node;
		pq->ptail = pq->ptail->next;
	}
}

//队头出队列
void QPop(Queue* pq)
{
	assert(!QEmpty(pq));
	QNode* del = pq->phead;
	pq->phead = del->next;
	free(del);
	del = NULL;
}

//返回队头元素
QDataType QFront(Queue* pq)
{
	assert(!QEmpty(pq));
	return pq->phead->data;
}

//返回队尾元素
QDataType QBack(Queue* pq)
{
	assert(!QEmpty(pq));
	return pq->ptail->data;
}

//队列元素个数
int QSize(Queue* pq)
{
	assert(pq);
	QNode* pcur = pq->phead;
	int cnt = 0;
	while (pcur)
	{
		cnt++;
		pcur = pcur->next;
	}
	return cnt;
}

 静态数组模拟队列

const int N = 1e6 + 10;
int q[N];
int hh, tt = -1;//队头hh,队尾tt,[hh,tt]中的就是队列中的元素 

//入队
void push(int x)
{
	q[++tt] = x;
} 
//出队
void pop()
{
	hh++;	
}
//队头
int front()
{
	return q[hh];	
} 
//队尾
int back()
{
	return q[tt];	
} 
//队列元素个数
int size()
{
	return tt - hh + 1;	
} 
//是否为空
bool empty()
{
	return tt < hh;	
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值