循环队列——c

// 循环队列.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdio.h"
#include  "malloc.h"

#define MAXSIZE 1024
typedef struct duilie{
	int data[MAXSIZE];
	int top;
	int foot;
}DuiLie;

//初始化
DuiLie *Init() {
	DuiLie *Q;
	Q = (DuiLie*)malloc(sizeof(duilie));
	Q->top = 0;
	Q->foot = 0;
	return Q;
}
//判断队满
bool Man(DuiLie *Q) {
	/***********************************************
		此处是应为队是环形的 top和foot为同一值就有
		两种可能 一个是绕了一圈了回来的 一个是两个
		是真的在同一个位置
		为了区分就只能损失一个空间
		当是绕了一圈的情况 那么foot加以那就等于top

		为什么用MAXSIZE求于呢?
		应为 top 和foot 在绕完一圈后不会自动归零
		所以当论完一圈时 那么top和foot都大于MAXSIZ
		如果在进行Q.data[top]或者Q.data[foot]操作就
		会超过 data数组的范围  所以每次都取余 这样就
		可以真实的找到top 和foot在环形队列中的真实位
		置  就无需归零 top和foot
	************************************************/
	if ((Q->foot + 1) % MAXSIZE == Q->top) {   
		return true;
	}
	return false;
}
//判断空
bool Kong(DuiLie *Q) {
	if (Q->top == Q->foot) {
		return true;
	}
	return false;
}
//入队
int Add(DuiLie *Q,int x) {
	if (!Man(Q)) {
		Q->data[Q->foot] = x;
		Q->foot = (Q->foot + 1) % MAXSIZE;
		return 1;
	}
	printf("队列满了\n");
	return 0;
}
//出队
int Out(DuiLie *Q) {
	if (!Kong(Q)) {
		printf("出队的数据为:%5d\n", Q->data[Q->top]);
		Q->top = (Q->top + 1) % MAXSIZE;
		return 1;
	}
	printf("队列为空\n");
	return 0;
}
//遍历
int Prints(DuiLie *Q) {
	int i = Q->top;
	while (i!=Q->foot) {
		printf("%5d\n", Q->data[i]);
		i++;
	}
	return 1;
}
int main()
{
	DuiLie *Q;
	Q = Init();
	//判断队空
	printf("是否为空  1为空 0为非空\n%d\n", Kong(Q));
	//入队
	Add(Q, 10); Add(Q, 20);
	Add(Q, 30); Add(Q, 40);
	printf("是否为空  1为空 0为非空\n%d\n", Kong(Q));
	//便利开始
	Prints(Q);
	//出队
	Out(Q); Out(Q);
	Out(Q); Out(Q);
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值