为防止队列溢出,通常会少用一个元素空间,即当队列空间的大小为maxsize时,有maxsize-1个元素的时候就认为队列已经满了
#include <stdio.h>
#include <stdlib.h>
#define maxsize 6
struct que
{
int arr[6];
int front;
int rear;
int length;
};
struct que *queInit(struct que *queue)
{
queue = (struct que*)malloc(sizeof(struct que));
queue->front = 0;
queue->rear = 0;
queue->length = 0;
printf("init success\n");
return queue;
}
int judgefull(struct que *queue){ //判断队列是否已经满了
if((queue->rear+1)%maxsize == queue->front){
return 1;
}else{
return 0;
}
}
int judgeempty(struct que *queue){ //判断队列是否为空队列
if(queue->front == queue->rear){
return 1;
}else{
return 0;
}
}
struct que *input(struct que *queue,int num) //入队
{
if(judgefull(queue) == 1){
printf("queue is full\n");
return queue;
}
queue->arr[queue->rear] = num;
queue->rear = (queue->rear+1)%maxsize; //为了使尾结点加1使用该方式,防止队列溢出
queue->length++;
printf("front is %d rear is %d data is %d\n",queue->front,queue->rear,queue->arr[queue->rear]);
return queue;
}
struct que *outQue(struct que *queue) //出队
{
if(judgeempty(queue) == 1){
printf("queue is empty\n");
}
printf("ourque num is %d\n",queue->arr[queue->front]);
queue->front = (queue->front+1)%maxsize;
queue->length--;
return queue;
}
void printque(struct que *queue) //打印队列
{
int i;
printf("data still inqueue\n");
for(i = queue->front;i<queue->rear;i++){
printf("data: %d\n",queue->arr[i]);
}
}
int main()
{
struct que *queue = NULL;
queue = queInit(queue);
queue = input(queue,1);
queue = input(queue,2);
queue = input(queue,3);
queue = input(queue,4);
queue = input(queue,5);
queue = input(queue,6);
printf("input success\n");
printque(queue);
queue = outQue(queue);
printque(queue);
return 0;
}