数组队列

  用数组实现的队列,也叫循环队列。就是定义一个数组,用两个下标front,rear表示队头和队尾。当队头和队尾相等时,队列为空。当队尾+1等于队头时,队列为满。这样会浪费一个内存空间。还可以定义一个变量,表示队列空满。

  我们下面介绍的是第一种方法。

我们可以把数组想象成一个圆形,数组当然不会是圆形,我们可以根据取余来判断数组的下标是否还在数组范围内。

我们在定义数组时会给定一个数组的大小,也就是MAXSIZE,大家会在很多函数中看到对MAXSIZE取余,这是为了保证数组的下标在有效的范围内。

当front和rear在同一个位置时,队列为空。

当front == rear + 1时,为满,也就是rear在front后面。(front == (rear+1)%MAXSIZE;)//判断条件。大家可以用实际的数字试一下。

aqueue.h

#ifndef _QUEUE_H
#define _QUEUE_H

#define MAXSIZE 10

typedef struct queue
{
int * arr;
int front;
int rear;
} Queue;

void q_init(Queue * queue);//初始化
void q_push(Queue * queue, const int data);//入队
void q_pop(Queue * queue);//出队
bool q_empty(Queue * queue);//为空
bool q_full(Queue * queue);//为满
int q_size(Queue * queue);//队大小
int q_front(Queue * queue);//队头元素
int q_back(Queue * queue);//队尾元素
void q_destroy(Queue * queue);//销毁

#endif //_QUEUE_h

aqueue.c

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

#include "aqueue.h"

void q_init(Queue * queue)
{
    queue->arr = (int *)malloc( sizeof(int) * MAXSIZE );//初始化数组
    assert(queue->arr != NULL);
    queue->front = 0;
    queue->rear = 0;
}

void q_push(Queue * queue, const int data)
{
    if ( q_full(queue) )
        return;
    queue->arr[queue->rear++] = data;//入队,队尾+1
    queue->rear = queue->rear % MAXSIZE;//如果队尾
}

void q_pop(Queue * queue)
{
    if ( q_empty(queue) )
        return;
    queue->front = ++queue->front % MAXSIZE;//front+1,对MAXSIZE取余
}

bool q_empty(Queue * queue)
{
    return queue->front == queue->rear;
}

bool q_full(Queue * queue)
{
    return queue->front == (queue->rear + 1) % MAXSIZE;


int q_size(Queue * queue)
{
    return (queue->rear - queue->front) % MAXSIZE;
}

int q_front(Queue * queue)
{
    assert( !q_empty(queue) );
    return queue->arr[queue->front];
}

int q_back(Queue * queue)
{
    assert( !q_empty(queue) );
    return queue->arr[queue->rear - 1];
}

void q_destroy(Queue * queue)
{
    free(queue->arr);
}

循环队列最好多入队出队的测试几次。因为可能下标没有转圈时是好使,转圈之后就不好使了。

还需要把数算明白。

 

posted @ 2016-01-20 21:30  Covit  阅读(2416)  评论(0编辑  收藏  举报