Today we learned about circular queues, which use continuous space and take mod operations to realize the loop, thereby reducing the waste of space. Please give me your advice.

Circular queue

What is a circular queue? The first thing to note is that circular queues are still implemented based on arrays. But just for the sake of visualization, we have two Pointers, front and rear, one to indicate the head of the queue and one to indicate the end of the queue. Ear and front chase each other. The chase process is the process of adding and removing the queue. If rear catches head, the queue is full, and if front catches rear, the queue is empty. Let a unit in the queue space idle, so that when the queue is not empty, there is at least one idle order between q.ear and q.front. We use the remainder, so that the two values do not run out of the maximum range, and can achieve the effect of bending, so for circular queue we must give a maximum MAXQSIZE.

The main function

#include<stdio.h>

#define MAXSIZE 100

typedef struct
{
    int element[MAXSIZE];
    int front;
    int rear;
}SeqQueue;// Array-based implementation, similar to the operation of the order table

void InitQueue(SeqQueue *Q)// Queue initialization
{
    Q->front=Q->rear=0;
}

void EnterQueue(SeqQueue *Q,int x)/ / team
{
    if((Q->rear+1)%MAXSIZE==Q->front) return;
    Q->element[Q->rear]=x;
    Q->rear=(Q->rear+1)%MAXSIZE;
}

void deleteQueue(SeqQueue *Q,int *x)/ / out of the team
{
    if(Q->front==Q->rear)  return ;// The queue is empty
    *x=Q->element[Q->front];
    Q->front=(Q->front+1)%MAXSIZE;
}

int main(a)
{     int x;
    SeqQueue Q;
    InitQueue(&Q);
    EnterQueue(&Q,1);
     EnterQueue(&Q,2);
      EnterQueue(&Q,3);
    deleteQueue(&Q,&x);
    printf("Entry element is 1, 2, 3, 4\ N");
    printf("The first element to exit is %d",x);
    return 0;

}

Copy the code

Run the screenshot: