队列是一种先进先出(FIFO)的线性表,只允许在一端(队尾)进行插入操作,另一端(队首)进行删除操作。

   队列的顺序存储结构是用一组连续的地址空间存放队列元素。在队尾进行插入元素使空间不断减少,而在队首进行删除操作使空间增多。顺序队列的弊端在于增加的空闲空间不能重新利用,而循环队列的首尾连接在一起,进行删除操作增加的空间能够重新利用。

   下面是代码:

#include<stdio.h>
#include<malloc.h>
#define OK 0
#define ERROR -1
#define OVERFLOW  -1
//循环队列的存储结构
#define MAXSIZE 100
typedef struct {
    int *base;
    int front;
    int rear;
}queue;
int init_queue(queue *q)
{
    q->base = (int*)malloc(MAXSIZE * sizeof(int));
    if(!q->base)
        exit(OVERFLOW);
    q->front = q->rear = 0;
    return OK;
}
int enqueue(queue * q, int e)
{
    if((q->rear + 1)%MAXSIZE == q->front )
        return ERROR;
    q->base[q->rear] = e;
    q->rear = (q->rear+1)%MAXSIZE;
    return OK;
}
int dequeue(queue * q, int *e)
{
    if(q->rear == q->front)
    return ERROR;
    *e = q->base[q->front];
    q->front = (q->front+1)% MAXSIZE;
    return OK;
}
int main()
{
    queue q;
    int i;
    int e;
    printf("init queue\n");
    init_queue(&q);
    printf("enqueue\n");
    for(i = 0; i < 10; i++)
    {
        enqueue(&q, i);
        printf("%3d", i);
    }
      
    printf("\ndequeue\n");
    for( i = 0; i < 10; i++)
    {
        dequeue(&q, &e);
        printf("%3d", e);
    }
    printf("\n");
    return 0;
}