循环队列的初始化,队空,队满,遍历,入队,出队操作
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
typedef struct Queue{
int *pBase;
int front;
int rear;
}QUEUE,* PQUEUE;
void init_queue(PQUEUE,int);
bool en_queue(PQUEUE,int,int);
bool queue_full(PQUEUE,int);
bool queue_empty(PQUEUE);
bool out_queue(PQUEUE,int*,int);
void traverse_queue(PQUEUE,int);
int main(){
QUEUE q;
int len=6;
int val;
printf("初始化循环队列!\n");
init_queue(&q,len);
printf("入队!\n");
en_queue(&q,len,6);
en_queue(&q,len,5);
en_queue(&q,len,4);
en_queue(&q,len,3);
en_queue(&q,len,2);
en_queue(&q,len,1);
traverse_queue(&q,len);
printf("出队!\n");
out_queue(&q,&val,len);
printf("出队元素为:%d\n",val);
out_queue(&q,&val,len);
printf("出队元素为:%d\n",val);
return 0;
}
void init_queue(PQUEUE pq,int len){
pq->pBase=(int *)malloc(sizeof(int)*len);
pq->front=0;
pq->rear=0;
printf("初始化队列成功!\n");
}
bool en_queue(PQUEUE pq,int len,int val){
if(queue_full(pq,len)) return false;
pq->pBase[pq->rear]=val;
pq->rear=(pq->rear+1)%len;
}
bool out_queue(PQUEUE pq,int* val,int len){
if(queue_empty(pq)) return false;
*val=pq->pBase[pq->front];
pq->front=(pq->front+1)%len;
}
bool queue_full(PQUEUE pq,int len){
if(pq->front==(pq->rear+1)%len){
return true;
}
return false;
}
bool queue_empty(PQUEUE pq){
if(pq->rear==pq->front){
return true;
}
return false;
}
void traverse_queue(PQUEUE pq,int len){
int p=pq->front;
while(p!=pq->rear){
printf("%3d",pq->pBase[p]);
p=(p+1)%len;
}
}