队列的实现

http://blog.csdn.net/leichelle/article/details/7546775

1.定义 :

队列(Queue):也是运算受限的线性表。是一种先进先出(First In First Out ,简称FIFO)的线性表。

队首(front) :允许进行删除的一端称为队首。
队尾(rear) :允许进行插入的一端称为队尾。
例如:排队购物。操作系统中的作业排队。先进入队列的成员总是先离开队列。

2.实现

struct queue {
    unsigned int elem[KEY_BUF_SIZE];//定长数组
    int front;
    int rear;
};

//定义一个全局的队列,初始化
static struct queue buf = {
    .front = 0,
    .rear = 0
};

static int queue_isfull(struct kqueue *q)
{
    return q->front == (q->rear + 1) % KEY_BUF_SIZE;
}

static int queue_isempty(struct kqueue *q)
{
    return q->front == q->rear;
}

static int queue_add(struct kqueue *q, unsigned int elm)
{
    if (queue_isfull(q))
        return -1;

    q->elem[q->rear] = elm;
    q->rear = (q->rear + 1) % KEY_BUF_SIZE;

    return 0;
}

static int queue_get(struct kqueue *q, unsigned int *elm)
{
    if (queue_isempty(q))
        return -1; 

    *elm = q->elem[q->front];

    q->front = (q->front + 1) % KEY_BUF_SIZE;
    return (*elm);

}
原文地址:https://www.cnblogs.com/chencesc/p/5090659.html