// 循环队列.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;
}
循环队列——c
最新推荐文章于 2022-11-08 18:57:15 发布