# circular buffer 的 sample

Practice: Implement a queue by circular buffer

Hint 1: use a macro to define the max queue length

Hint 2: declare a structure to record

the array

the start index

the end index

Hint 3: write a function to initialize the queue

Hint 4: write two functions to test emptiness/fullness of the queue

Hint 5: write a function to enqueue

Hint 6: write a function to dequeue

Hint 7: use assertions to detect invalid enqueue/dequeue conditions

Hint 8: write a function to print the available data items in the queue

Hint 9: write a test program to simulate the buffering of a sequence of data

Rating
• Wu
Lv 5

#include <assert.h>

#define MAX_QUEUE 10

typedef struct

{ int data[MAX_QUEUE];

int start;

int end;

int ndata;

} BUFFER;

void initBuffer(BUFFER *buf)

{

buf->start = buf->end = buf->ndata = 0;

}

int isEmpty(BUFFER *buf)

{

return (buf && !buf->ndata);

}

int isFull(BUFFER *buf)

{

return (buf && buf->ndata == MAX_QUEUE);

}

void enQueue(BUFFER *buf, int num)

{ assert(buf && !isFull(buf));

buf->data[buf->end++] = num;

buf->end %= MAX_QUEUE;

++buf->ndata;

}

int deQueue(BUFFER *buf)

{ int data;

assert(buf && !isEmpty(buf));

data = buf->data[buf->start++];

buf->start %= MAX_QUEUE;

--buf->ndata;

return data;

}

void printData(BUFFER *buf)

{ int i,n;

if (buf && !isEmpty(buf))

for (n=0,i=buf->start;n<buf->ndata; ++n, ++i, i%=MAX_QUEUE) printf("%d\n",buf->data[i]);

}

void main()

{ BUFFER buf;

int i;

initBuffer(&buf);

for (i=1; i<=MAX_QUEUE; ++i) enQueue(&buf, i);

printf("queued data:\n");

printData(&buf);

printf("dequeuing %d\n",deQueue(&buf));

printf("dequeuing %d\n",deQueue(&buf));

enQueue(&buf,-1);

enQueue(&buf,-2);

printf("updated data:\n");

printData(&buf);

}