#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
/*
数组实现
循环队列,最后一个元素为空
初始化
入队
出队
*/
typedef struct queue{
int front;//队列的第一个元素
int rear;//队列的最后有效元素的后一个元素下标
int * pBase;//指向队列的首地址
int len; //数组的长度
}QUEUE, *PQUEUE;
void init(PQUEUE, int);//初始化队列
void enqueue(PQUEUE, int);//入队
bool is_full(PQUEUE);
void traverse(PQUEUE);//遍历
bool is_empty(PQUEUE);
void out(PQUEUE, int *);//出队
int main(void)
{
QUEUE Q;
int length = 6;
int val;
init(&Q, length);
enqueue(&Q, 3);//[3]
enqueue(&Q, 4);//[3,4]
enqueue(&Q, 2);//[3,4,2]
enqueue(&Q, 6);//[3,4,2,6]
enqueue(&Q, 1);//[3,4,2,6,1]
enqueue(&Q, 1);//[3,4,2,6,1]
traverse(&Q);
out(&Q, &val);//[3,4,2,6]
traverse(&Q);
return 0;
}
void init(PQUEUE pQ, int length)
{
pQ->pBase = (int *)malloc(sizeof(int)*length);//在堆中开辟一块连续空间,长度为length
pQ->front = 0;// 队列中第一个元素 ,指向第一个元素
pQ->rear = 0;//初始化时和和front同时指向首元素
pQ->len = length;
}
bool is_full(PQUEUE pQ)
{
if(pQ->front == (pQ->rear+1) % pQ->len) return true;//求余的作用体现循环队列
else return false;
}
//入队操作
void enqueue(PQUEUE pQ, int val)
{
if(is_full(pQ))
{
return;
}
else
{
pQ->pBase[pQ->rear] = val;
pQ->rear = (pQ->rear+1) % pQ->len;
}
}
//遍历队列
void traverse(PQUEUE pQ)
{
int i = pQ->front;
while(i != pQ->rear)
{
printf("%d ", pQ->pBase[i]);
i = (i+1) % pQ->len;
}
printf("\n");
}
bool is_empty(PQUEUE pQ)
{
if(pQ->rear == pQ->front) return true;
else return false;
}
//出队操作
void out(PQUEUE pQ, int * pVal)
{
if(is_empty(pQ))
{
return;
}
else
{
*pVal = pQ->pBase[pQ->front];
pQ->front = (pQ->front+1) % pQ->len;
}
}