欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构——循环队列的基本操作(C语言实现)

程序员文章站 2022-05-04 17:25:14
...

1、定义

#define QUEUE_DEFAULT_SIZE 8
typedef struct CycleSeqQueue
{
	ElemType *base;
	int       capacity;
	int       front;
	int       rear;
}CycleSeqQueue;

2、判空、判满

bool IsFull(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	return ((pcq->rear + 1) % (pcq->capacity + 1)) == pcq->front;
}
bool IsEmpty(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	return pcq->front == pcq->rear;
}

3、初始化

void CycleSeqQueueInit(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	pcq->capacity = QUEUE_DEFAULT_SIZE;
	pcq->base = (ElemType*)malloc(sizeof(ElemType)* (pcq->capacity + 1));
	pcq->front = pcq->rear = 0;
}

4、入队、出队

void CycleSeqQueueEn(CycleSeqQueue *pcq, ElemType x)
{
	assert(pcq != NULL);
	if (IsFull(pcq))
	{
		printf("队列已满, %d 不能入队.\n", x);
		return;
	}
	pcq->base[pcq->rear] = x;
	pcq->rear = (pcq->rear + 1) % (pcq->capacity + 1);
}

void CycleSeqQueueDe(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	if (IsEmpty(pcq))
	{
		printf("队列以空, 不能出队.\n");
		return;
	}
	pcq->front = (pcq->front + 1) % (pcq->capacity + 1);
}

5、取对头元素

ElemType CycleSeqQueueFront(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	assert(!IsEmpty(pcq));
	return pcq->base[pcq->front];
}

6、求队列元素个数

int CycleSeqQueueSize(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	int size = 0;
	for (int i = pcq->front; i != pcq->rear;)
	{
		size++;
		i = (i + 1) % (pcq->capacity + 1);
	}
	return size;
}

7、打印

void CycleSeqQueueShow(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	for (int i = pcq->front; i != pcq->rear;)
	{
		printf("%d ", pcq->base[i]);
		i = (i + 1) % (pcq->capacity + 1);
	}
	printf("\n");
}

8、摧毁

void CycleSeqQueueDestroy(CycleSeqQueue *pcq)
{
	assert(pcq != NULL);
	free(pcq->base);
	pcq->base = NULL;
	pcq->capacity = pcq->front = pcq->rear = 0;
}

测试用例和运行结果

数据结构——循环队列的基本操作(C语言实现)