顺序存储队列-用C语言描述

#include<stdio.h>
#include<stdlib.h>

/*
队列的顺序存储(循环队列)
方法:少用一个元素空间。
*/

typedef int ElementType;
typedef int Position;
typedef struct QNode * PtrToNode;

struct QNode
{
	ElementType * Data;		/*存储元素的数组*/
	Position Front, Rear;		/*队列的头、尾指针*/
	int MaxSize;		/*队列的最大容量*/
};

typedef PtrToNode Queue;
ElementType ERROR = -1;

Queue CreateQueue(int MaxSize) {
	/*创建队列*/
	Queue Q = (Queue)malloc(sizeof(struct QNode));
	Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
	Q->Front = Q->Rear = 0;
	Q->MaxSize = MaxSize;
	return Q;
}

bool IsFull(Queue Q) {
	/*判断队列是否满
	队列满:队尾指针+1就会从后面赶上队头指针
	*/
	return((Q->Rear + 1) % Q->MaxSize == Q->Front);
}

bool AddQ(Queue Q, ElementType X) {
	/*
	入队
	*/
	if (IsFull(Q)) {
		printf("队列满\n");
		return false;
	}
	else {
		Q->Rear = (Q->Rear + 1) % Q->MaxSize;
		Q->Data[Q->Rear] = X;
		return true;
	}
}

bool IsEmpty(Queue Q) {
	/*
	判断队列是否空
	*/
	return(Q->Front == Q->Rear);
}

ElementType DeleteQ(Queue Q) {
	/*出队*/
	if (IsEmpty(Q)) {
		printf("队列空\n");
		return ERROR;
	}
	else {
		Q->Front = (Q->Front + 1) % Q->MaxSize;
		return Q->Data[Q->Front];
	}
}

void SeqQueueDemo() {
	printf("===========初始化最大长度为11的队列=============\n");
	Queue Q = CreateQueue(11);
	printf("==========依次向队列加入1-10================\n");
	for (int i = 1;i <= 10;i++)
		AddQ(Q, i);
	printf("==========尝试继续向队列加入11================\n");
	AddQ(Q, 11);
	printf("==========依次从队列取出10个数据================\n");
	for (int j = 1;j <= 10;j++) {
		ElementType tmp = DeleteQ(Q);
		printf("%d\t", tmp);
	}
	printf("\n===========尝试继续取一个数据===================\n");
	ElementType x = DeleteQ(Q);
}

int main() {
	SeqQueueDemo();
	return 0;
}

运行结果:

===========初始化最大长度为11的队列=============
==========依次向队列加入1-10================
==========尝试继续向队列加入11================
队列满
==========依次从队列取出10个数据================
1    2    3    4    5    6    7    8    9    10    
===========尝试继续取一个数据===================
队列空

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WUYANGEZRA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值