数据结构——线性表(队列)

数据结构线性表(队列)

今天给大家介绍一下数据结构线性表里关于队列的知识和相关功能接口的实现。

1、概念

概念:队列是一种特殊的线性表,它只允许在一端进行插入数据操作,在另一端进行删除操作,队列遵循先进先出的特性。(类似于排队,优先排队的优先服务,后来的后排队,不允许插队)
入队列:入队列也称为队列的插入操作,进行插入操作的一端称为队尾
出队列:出队列也称为队列的删除操作,进行删除操作的一端称为队头

2、结构

在这里插入图片描述

3、队列的实现

队列可以以数组和链表的结构实现,使用链表的结构实现更优一些,使用数组结构在出队列时效率比较低。

3.1顺序队列

借助数组实现队列。

3.1.1结构
#define SEQ_QUEUE_DEFAULT_SIZE 6
#define SEQ_QUEUE_INC_SIZE     3

typedef struct SeqQueue
{
   
	ElemType *base;
	int   capacity;
	int      front;
	int      rear;
}SeqQueue;

在这里插入图片描述

3.1.2接口实现

主要实现顺序队列的初始化、扩容、判空、判满、入队、出队、取队头元素、打印等操作。

void SeqQueueInit(SeqQueue *psq);//初始化
static bool _SeqQueueInc(SeqQueue *psq);//扩容
bool SeqQueueIsFull(SeqQueue *psq);//判满
bool SeqQueueIsEmpty(SeqQueue *psq);//判空
void SeqQueueEnque(SeqQueue *psq, ElemType x);//入队
void SeqQueueDeque(SeqQueue *psq);//出队
ElemType SeqQueueFront(SeqQueue *psq);//取队头元素
void SeqQueuePrint(SeqQueue *psq);//打印
(1)、初始化
void SeqQueueInit(SeqQueue *psq)
{
   
	psq->base = (ElemType*)malloc(sizeof(ElemType)*SEQ_QUEUE_DEFAULT_SIZE);
	assert(psq != NULL);
	psq->capacity = SEQ_QUEUE_DEFAULT_SIZE;
	psq->front = psq->rear = 0;
}
(2)、扩容
static bool _SeqQueueInc(SeqQueue *psq)
{
   
	ElemType *new_base = (ElemType*)realloc(psq->base, sizeof(ElemType)*(psq->capacity + SEQ_QUEUE_INC_SIZE));
	if (new_base == NULL)
		return false;
	psq->base = new_base;
	psq->capacity += SEQ_QUEUE_INC_SIZE;
	return true;
}
(3)、判满
bool SeqQueueIsFull(SeqQueue *psq)
{
   
	assert(psq != NULL);
	return psq->rear >= psq->capacity;
}
(3)、判空
bool SeqQueueIsEmpty(SeqQueue *psq)
{
   
	assert(psq != NULL);
	return psq->front==psq->rear;
}
(5)、入队
void SeqQueueEnque(SeqQueue *psq, ElemType x)
{
   
	assert(psq != NULL);
	if (SeqQueueIsFull(psq))
	{
   
		printf("队列空间已满,%d不能入队.\n", x);
		return;
	}
	psq->base[psq->rear++] = x;
}
(6)、出队
void SeqQueueDeque(SeqQueue *psq)
{
   
	assert(psq != NULL);
	if (SeqQueueIsEmpty(psq))
	{
   
		printf("队列已空,不能出队.\n");
		return;
	}
	psq->front++;
}
(7)、取队头元素
ElemType SeqQueueFront(SeqQueue *psq)
{
   
	assert(psq != NULL);
	if (SeqQueueIsEmpty(psq))
	{
   
		printf("队列已空,不能取队头元素.\n");
		return;
	}
	return psq->base[psq
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值