队列的数组实现

queen.h:

#include <stdlib.h>

 

#define QUEUE_TYPE char

 

void insert(QUEUE_TYPE value);

void delete();

 

QUEUE_TYPE first();

 

int is_empty();

int is_full();

 

queen.c:

#include "queen.h"

#include <stdio.h>

#include <assert.h>

 

#define QUEUE_SIZE 5

 

/*

** 使用不完全填满数组的技巧,不好理解

*/

/*

#define ARRAY_SIZE (QUEUE_SIZE + 1)

 

static QUEUE_TYPE queue[ARRAY_SIZE];

static size_t front = 1;

static size_t rear = 0;

 

void insert(QUEUE_TYPE value)

{

       assert(!is_full());

 

       rear = (rear + 1) % ARRAY_SIZE;

       queue[rear] = value;

}

 

void delete()

{

       assert(!is_empty());

 

       front = (front + 1) % ARRAY_SIZE;

}

 

QUEUE_TYPE first()

{

       assert(!is_empty());

      

       return queue[front];

}

 

int is_empty()

{

       return (rear + 1) % ARRAY_SIZE == front;

}

 

int is_full(void)

{

       return (rear + 2) % ARRAY_SIZE == front;

}

*/

 

/*

** 引入一个全局变量

*/

static QUEUE_TYPE queue[QUEUE_SIZE];

 

static size_t cur_size = 0;

static front = 0;

static rear = 0;

 

void insert(QUEUE_TYPE value)

{

       assert(!is_full());

 

       rear = (rear+1) % QUEUE_SIZE;

      

       queue[rear] = value;

 

       cur_size++;

}

 

void delete()

{

       assert(!is_empty());

 

       front = (front+1) % QUEUE_SIZE;

 

       cur_size--;

}

 

QUEUE_TYPE first()

{

       assert(!is_empty());

 

       return queue[front];

}

 

int is_empty()

{

       return cur_size == 0;

}

 

int is_full()

{

       return cur_size == QUEUE_SIZE;

}

 

test.c:

#include "queen.h"

#include <stdio.h>

 

void main()

{

       insert('a');

       delete();

       insert('a');

       delete();

       insert('a');

       delete();

       insert('a');

       delete();

 

       insert('a');

       delete();

       //insert('a');

       //insert('a');

       //insert('a');

       //insert('a');

       //insert('a');

       //delete();

 

       //printf("first() = %c/n", first());

 

       printf("is_empty: %d/n", is_empty());

       printf("is_full: %d/n", is_full());

}

你可能感兴趣的:(队列的数组实现)