队列的相关知识

目录

 创建

初始化

销毁

头插

尾删

取出头

取出尾

数字个数

判空


队列的性质与特征

性质:一种先进先出的线性表 

特征:FIFO(先进先出)

实现:用数组和链表的都可以

例子:在生产者消费者模型用到了循环链表

模型:未来曲风队列是满的还是不满的,我们多加一个空间保证rear+1是front

 创建

typedef  struct Queue//避免老是传二级指针
{
	QNode* phead;
	QNode* tail;
	 int size;
 }Queue;

typedef struct QNode
{
	struct QNode* next;
	DataType val;
}QNode;

初始化

void QueueInit(Queue* p)
{
	assert(p);
	p->phead = p->tail=NULL;
	p->size = 0;
}

销毁

void QueueDestroy(Queue* p)
{
	assert(p);
	QNode* cur = p->phead;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	p->phead = p->tail = NULL;
	p->size = 0;
}

头插

void QPush(Queue* p, DataType x)//插入先创建空间
{
	assert(p);
	QNode* newNode = (QNode*)malloc(sizeof(QNode));
	if (newNode = NULL)
	{
		printf("malloc failed");
		return;
	}
	newNode->next = NULL;
	newNode->val = x;

	if (p->phead == NULL)
	{
		p->phead = p->tail = newNode;
	}
	else
	{
		p->tail->next = newNode;	
		p->tail = newNode;
	}
	p->size++;
}

尾删

void Qpop(Queue* p)
{
	assert(p);
	assert(p->size);
	
	if (p->phead->next == NULL)
	{
		free(p->phead);
		p->phead = p->tail = NULL;
	}
	else
	{
		QNode* next = p->phead->next;
		free(p->phead);
		p->phead = next;
	}
	p->size--;
}

取出头

DataType QueueFront(Queue* p)
{
	assert(p);
	assert(p->phead);
	return p->phead->val;
}

取出尾

DataType QueueBack(Queue* p)
{
	assert(p);
	assert(p->tail);
	return p->tail->val;
}

数字个数

int QSize(Queue* p)
{
	assert(p);
	return p->size;
}

判空

bool QueueEmpty(Queue* p)
{
	assert(p);
	if (p->size == 0)
		return true;
	else
		return false;
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值