LoopQueue.h
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
typedef int Elemtype;
#define MAX_SIZE 8
typedef struct Queue
{
Elemtype* base;
int front;
int rear;
}Queue;
void InitQueue(Queue* Q);
void EnQueue(Queue* Q, const Elemtype x);
void ShowQueue(const Queue* Q);
void DeQueue(Queue* Q);
int Length(const Queue* Q);
void GetHead(const Queue* Q, Elemtype* v);
void ClearQueue(Queue* Q);
void DestroyQueue(Queue* Q);
LoopQueue.cpp
#include "LoopQueue.h"
void InitQueue(Queue* Q)
{
assert(Q != NULL);
Q->base = (Elemtype*)malloc(sizeof(Elemtype)*MAX_SIZE);
assert(Q->base != NULL);
Q->front = Q->rear = 0;
}
void EnQueue(Queue* Q, const Elemtype x)
{
assert(Q != NULL);
assert((Q->rear + 1) % MAX_SIZE != Q->front);
Q->base[Q->rear] = x;
Q->rear = (Q->rear + 1) % MAX_SIZE;
}
void ShowQueue(const Queue* Q)
{
assert(Q != NULL);
for (int i = Q->front; i != Q->rear; )
{
printf("%d ", Q->base[i]);
i = (i + 1) % MAX_SIZE;
}
printf("\n");
}
void DeQueue(Queue* Q)
{
assert(Q != NULL);
assert(Q->front != Q->rear);
Q->front = (Q->front + 1) % MAX_SIZE;
}
int Length(const Queue* Q)
{
return Q->rear - Q->front;
}
void GetHead(const Queue* Q, Elemtype* v)
{
assert(Q != NULL);
assert(Q->front != Q->rear);
*v = Q->base[Q->front];
}
void ClearQueue(Queue* Q)
{
assert(Q != NULL);
Q->front = Q->rear = 0;
}
void DestroyQueue(Queue* Q)
{
assert(Q != NULL);
ClearQueue(Q);
free(Q->base);
Q->base = NULL;
}