It is not difficult to implement a loop queue in C language. The key point is to judge the queue "empty" and "full" status.
As described in the C and pointers, there are two ways to make judgments about the queue's empty and full state. In the array hollow an element is not filled in, at the beginning, the set tail is 0, front is 1, thus, the realization to waste queue buffer two element space: Queue null: (tail+1)% Queue_size = = Front Queue full: (tail+2)% q Ueue_size = = Front defines a variable to record the number of elements in the queue, to determine the queue's empty and full directly look at the value of the variable
The 2nd type is used in this article:
#include <stdio.h>
#define QUEUE_SIZE 5
#define QUEUE_TYPE int
static int queue_cnt = 0;
static int queue_front = 0;
static int queue_tail = 0;
Static Queue_type queue_buf[queue_size];
int Is_empty ()
{return
queue_cnt = = 0;
}
int Is_full ()
{return
queue_cnt = = queue_size;
}
int Insert (Queue_type e)
{
if (Is_full ()) {
printf ("QUEUE is full!!! \ n ");
return 0;
}
Queue_buf[queue_tail] = e;
Queue_tail = (queue_tail + 1)% Queue_size;
queue_cnt++;
return 1;
}
int delete ()
{
if (Is_empty ()) {
printf ("Queue is empty!!! \ n ");
return 0;
}
Queue_front = (queue_front + 1)% Queue_size;
queue_cnt--;
return 1;
}
int main ()
{
insert (3);
Insert (3);
Insert (3);
Insert (3);
Insert (3);
Delete ();
Insert (3);
Insert (3);
return 0;
}