环形队列的定义与操作



看代码理解吧。。。

/*************************************************************************
    > File Name: queue_2.c
    > Author: Netcan
    > Mail: 1469709759@qq.com 
    > Created Time: 2014/12/23 16:09:30
 ************************************************************************/

#include<stdio.h>
#include<malloc.h>

struct Queue { // 定义一个环形队列(静态队列)
	int * pBase; // 存放数据的数组
	int front; // 队列首下标
	int rear; // 队列尾下标,指向最后一个有效数据的后一个
	int size; // 队列大小
};

void init_Queue(Queue *Q); // 初始化队列
bool is_empty_Queue(Queue *Q); // 检测队列是否为空
bool is_full_Queue(Queue *Q); // 检测队列是否满
bool in_Queue(Queue *Q, int val); // 入队
bool out_Queue(Queue *Q); // 出队
void traverse_Queue(Queue *Q); // 遍历队列

int main() {
	Queue Q; // 声明一个队列
	init_Queue(&Q); // 初始化
	if(is_empty_Queue(&Q)) // 检测队列是否为空
		puts("Queue empty.");
	in_Queue(&Q, 0); // 入队
	in_Queue(&Q, 1);
	in_Queue(&Q, 2);
	in_Queue(&Q, 3);
	in_Queue(&Q, 4);
	in_Queue(&Q, 5);
	in_Queue(&Q, 6);
	in_Queue(&Q, 7);
	in_Queue(&Q, 8);
	in_Queue(&Q, 9);
	if(is_full_Queue(&Q)) // 检测队列是否满
		puts("Queue full.");
	traverse_Queue(&Q); // 输出队列
	out_Queue(&Q); // 出队
	out_Queue(&Q);
	traverse_Queue(&Q);

	return 0;
}

void init_Queue(Queue *Q)
{
	Q->size = 11; // 设队列大小为11
	Q->pBase = (int *)malloc(sizeof(int)*Q->size); // 分配内存用于存储数据
	Q->rear = Q->front = 0; // 初始化首尾下标
	return;
}

bool is_empty_Queue(Queue *Q)
{
	if(Q->front == Q->rear) // 如果首尾下标相等则空
		return true;
	else 
		return false;
}

bool is_full_Queue(Queue *Q)
{
	if( (Q->rear + 1)%Q->size == Q->front ) // 如果尾下标的下一个是首下标则满
		return true;
	else
		return false;
}

bool in_Queue(Queue *Q, int val)
{
	if( is_full_Queue(Q) ) // 满的话就不能入队
		return false; 
	Q->pBase[Q->rear] = val; // 入队
	Q->rear = (Q->rear + 1)%Q->size; // 尾下标后移
	return true;
}

bool out_Queue(Queue *Q)
{
	if( is_empty_Queue(Q) ) // 如果空的话就不能出队
		return false;
	Q->front = (Q->front + 1) % Q->size; // 首下标后移表示出队
	return true;
}

void traverse_Queue(Queue *Q)
{
	for(int i = Q->front; i != Q->rear; i = (i+1)%Q->size) // i用于输出元素的下标,当i等于尾下标输出结束
		printf("%3d",Q->pBase[i]);
	puts("");
	return;
}



运行图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值