#include <stdio.h>
#include <malloc.h>
#define LEN 6
typedef struct queue{
int * pBase; //队列的数组.
int front; //出队点.
int rear; //入队点.
} QUEUE, * PQUEUE;
void init(PQUEUE);
int en_queue(PQUEUE, int);
int full_queue(PQUEUE);
void print_queue(PQUEUE);
int out_queue(PQUEUE, int *);
int empty(PQUEUE pQ);
int main(void) {
QUEUE Q;
int val;
init(&Q);
en_queue(&Q, 1);
en_queue(&Q, 2);
en_queue(&Q, 3);
en_queue(&Q, 4);
en_queue(&Q, 5);
print_queue(&Q);
if(out_queue(&Q, &val)){
printf("出队:%d\n", val);
}
if(out_queue(&Q, &val)){
printf("出队:%d\n", val);
}
en_queue(&Q, 7);
en_queue(&Q, 8);
print_queue(&Q);
return 0;
}
//队列初始化方法.
void init(PQUEUE pQ){
pQ->pBase = (int *)malloc(sizeof(int) * LEN);
pQ->front = 0;
pQ->rear = 0;
}
//判断队列是否满.
//(pQ->rear+1) % LEN 可实现循环自加.
//循环队列核心方法.
int full_queue(PQUEUE pQ){
if((pQ->rear+1) % LEN == pQ->front){
return 1;
} else {
return 0;
}
}
//入队方法.
int en_queue(PQUEUE pQ, int val){
if(full_queue(pQ)){
return 0;
} else {
pQ->pBase[pQ->rear] = val;
pQ->rear = (pQ->rear + 1) % LEN;
return 1;
}
}
//打印队列里的值.
void print_queue(PQUEUE pQ){
int i = pQ->front;
while(i != pQ->rear){
printf("%d\n", pQ->pBase[i]);
i = (i + 1) % LEN;
}
}
//判断队列是不是为空.如果为空.就不能出列.
int empty(PQUEUE pQ){
if(pQ->front == pQ->rear){
return 1;
} else {
return 0;
}
}
//出列方法.
int out_queue(PQUEUE pQ, int * pVal){
if( empty(pQ) ){
return 0;
} else {
*pVal = pQ->pBase[pQ->front];
pQ->front = (pQ->front + 1) % LEN;
return 1;
}
}
循环Queue(队列)
最新推荐文章于 2023-12-02 16:43:15 发布