/* 队列:
1、什么叫队列:一个能够实现先进先出的存储结构
2、队列的分类:链式队列,静态队列(数组队列)
3、队列的参数:front,rear
静态队里:
1、静态队列为什么是循环队列:队列先进先出,不管我入队还是出队,front rear都得++,往上走。
当删除的时候,f往上走,内存就泄露。所以我需要用循环来解决这个问题。内存最大利用化。
2、循环队列需要几个参数来确定:循环队列需要两个参数来确定,front,rear
3、循环队列各个参数的含义:front,rear是数组的下标,而不是指针
front:表示队列的第一个元素
rear:表示队列最后一个有效元素的下一个
队列的初始化:front rear都为零的时候
front rear的值相等,但不一定为零
4、循环队列入队伪算法:将值存入r所代表的位置,然后把r往后走,
错误的写法:rear=rear+1;rear=(rear+1)% 队列的长度
5、循环队列出队伪算法:front=(front+1)% 数组的长度
6、如何判断循环队列为空:front=rear;
7、如何判断循环队列已满:front=(rear+1)% 数组的长度,否则不满
队列的长度是n,队列只能存储n-1个值,必须有一个为空,便于操作
8、队列的应用:凡是与时间有关的,都有队列的影子
*/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct queue
{
int * pBase;
int front;
int rear;
}Queue, * pQueue;
typedef int bool;
#define true 1
#define false 0
void init_queue(Queue *);
bool out_queue(Queue *, int *);
bool is_empty(pQueue);
bool is_full(pQueue);
bool en_queue(pQueue, int);
void traverse_queue(const pQueue);
int main(void)
{
Queue Q;
int val;
init_queue(&Q);
en_queue(&Q, 44);
en_queue(&Q, 38);
en_queue(&Q, 23);
en_queue(&Q, 49);
en_queue(&Q, 65);
en_queue(&Q, 97);
en_queue(&Q, 8);
en_queue(&Q, 9);
traverse_queue(&Q);
out_queue(&Q, &val);
traverse_queue(&Q);
out_queue(&Q, &val);
return 0;
}
void init_queue(Queue * pQ)
{
pQ->pBase=(int *)malloc(sizeof(int)*7);//个体存储+个体关系的存储
if(pQ->pBase==NULL)
{
puts("内存分配失败!");
exit(-1);
}
pQ->front=0;
pQ->rear=0;
return;
}
bool out_queue(pQueue pQ, int * pVal)
{
if( is_empty(pQ) )
return false;
*pVal=pQ->pBase[pQ->front];
printf("出队的数是:%d\n",*pVal);
pQ->front=(pQ->front+1)%7;
return true;
}
bool is_empty(pQueue pQ)
{
if( pQ->front== pQ->rear )
return true;
else
return false;
}
bool en_queue(pQueue pQ, int val)
{
if( is_full(pQ) )
return false;
else
{
pQ->pBase[pQ->rear]=val;
pQ->rear=(pQ->rear+1)%7;
return true;
}
}
bool is_full(pQueue pQ)
{
if( (pQ->rear+1)%7==pQ->front )
return true;
else
return false;
}
void traverse_queue(const pQueue pQ)
{
while( (pQ->front+1)%7 != pQ->rear )
{
printf("%d\t",pQ->pBase[pQ->front]);
pQ->front=(pQ->front+1)%7;
}
putchar('\n');
return;
}