The C language implements circular queues

  • 2020-10-31 21:55:59
  • OfStack

This article shares the specific code of C language loop queue for your reference. The specific content is as follows

Notes:

1. Circular queue is the sequential representation and implementation of the queue. Because it is tail in and head out, unlike the sequence stack, the sequence queue needs to be fabricated into a circular space so that it can be inserted from the head space after the tail is filled.
2. Array queues can also be used, that is, sequential queues that cannot be dynamically grown, so that there is no need to take the maximum modulus each time to form the annular space. The tail pointer increases by 1 each time a new queue header element is inserted, and by 1 each time a queue header element is removed.
3. The tail pointer will appear before the head pointer, so the loop queue should not be used when the usage size cannot be estimated.
4. Add 1 % MAXQUEUE to every pointer increment expression to keep each increment within range.


#include<stdio.h>
#include<stdlib.h>
#define MAXQUEUE 100
typedef struct
{
 int *base;
 int front;
 int rear;
}SqQueue, *Sqqueue;
 
Sqqueue Creat(Sqqueue q);
void Enqueue(Sqqueue q, int e);
void Dequeue(Sqqueue q, int *e);
void Traverse(Sqqueue q);
 
int main()
{
 SqQueue q;
 int e;
 Sqqueue p = Creat(&q);
 Traverse(p);
 Dequeue(p, &e);
 Traverse(p);
 printf("the number that was deleted is :%d", e);
 return 0;
}
 
Sqqueue Creat(Sqqueue q)
{
 Sqqueue p = q;
 p->base = (int *)malloc(MAXQUEUE * sizeof(int));// Note here that instead of a chain, the whole piece of data space is opened up base As the base 
 p->front = p->rear = 0;             
 for (int i = 1; i < 10; i++)
 Enqueue(p, i);
 return p;
}
void Enqueue(Sqqueue q, int e)
{
 if ((q->rear + 1) % MAXQUEUE == q->front) // If the tail pointer goes down 1 One is the header pointer, which is treated as a full queue (underutilized 1 Space). Otherwise, the head pointer equals the tail pointer is ambiguous. 
 exit(1);
 q->base[q->rear] = e;
 q->rear = (q->rear + 1) % MAXQUEUE;
 
}
void Dequeue(Sqqueue q, int *e)
{
 if (q->front == q->rear)
 exit(1);
 (*e) = q->base[q->front];
 q->front = (q->front + 1) % MAXQUEUE;
}
void Traverse(Sqqueue q)
{
 for (int i = q->front; q->rear != i; i = (i + 1) % MAXQUEUE)
 printf("%d->", q->base[i]);
 printf("NULL\n");
}

Related articles: