循环单链表创建队列

本文介绍了一个队列数据结构的实现,它支持O(1)的入队和出队操作,并在出队后能重复利用空间,保持队列总空间不变。通过顺序循环存储的方式,详细讲解了初始化、判断空满、入队和出队的函数实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*请设计一个队列,要求满足:1.初始时队列为空;2.入队时,允许增加队列占用空间;3.出队后,出队元素所占用的
空间可重复使用,即整个队列所占用的空间值增不减;4.入队操作和出队操作的时间复杂度始终保持为O(1)*/
//想法:与顺序循环存储队列相似
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
	ElemType data;
	struct LNode *next;
}LNode;
typedef struct{
	LNode *front,*rear;
}Queue;

void InitQueue(Queue &Q)
{
	Q.front = Q.rear = (LNode*)malloc(sizeof(LNode));
	Q.rear->next = Q.front;
}

bool IsEmpty(Queue Q)
{
	if(Q.front == Q.rear)
		return true;
	else
		return false;
}

bool IsOverflow(Queue Q)
{
	if(Q.rear->next == Q.front)
		return true;
	else
		return false;
}

bool EnQueue(Queue &Q,ElemType x)
{
	if(IsOverflow(Q))
	{
		LNode *s = (LNode*)malloc(sizeof(LNode));
		Q.rear->data = x;
		s->next = Q.rear->next;
		Q.rear->next = s;
		Q.rear = s;
	}else{
		Q.rear->data = x;
		Q.rear = Q.rear->next;
	}
	return true;
}

bool DeQueue(Queue &Q,ElemType &x)
{
	if(IsEmpty(Q))
		return false;
	x = Q.front->data;
	Q.front = Q.front->next;
	return true;
}

void main()
{
	Queue Q;
	ElemType getVal;
	InitQueue(Q);
	EnQueue(Q,1);
	EnQueue(Q,2);
	EnQueue(Q,3);
	DeQueue(Q,getVal);
	DeQueue(Q,getVal);
	printf("%d\n",getVal);
}

如有问题,欢迎随时指出,与讨论~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值