C language realizes the basic operation of circular (sequential) queue

Time:2021-10-24
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 10
#define TRUE 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct
{
    ElemType *base;  // Array base address, dynamically allocate memory
    int front;   // Head pointer
    int rear;      // Tail pointer
}Queue;
Status InitQueue(Queue* Q);   // initialization
Status InsertQueue(Queue* Q, ElemType e);//  Join the team
Status DeleteQueue(Queue* Q, ElemType* e); // Out of the team
Status LengthQueue(Queue* Q);  // Get Captain
void DstoryQueue(Queue *Q); // Destruction team
int main()
{
    Queue Q;
    ElemType e;
    int n, a;
    if (InitQueue(&Q) == 1)
        Printf ("create circular queue succeeded! \ n");
    Printf ("enter the number of elements inserted at the end of the queue:");
    scanf("%d", &n);
    Printf ("insert end of queue element:");
    If (n! = 0) // judge whether the queue is empty
    {
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &e);
            a = InsertQueue(&Q, e);

        }
    }
    else
        a = -1;
    if (a == 1) {
        Printf ("insert succeeded! \ n");
        Printf ("the leader is:% d \ n", lengthqueue & Q));
    }
        if (a==0)
        Printf ("the queue is full! Cannot continue inserting! \ n");
    if (DeleteQueue(&Q, &e) == 1)
    {
        Printf ("delete the first element of the queue as:% d \ n", e);
    }
    else
        Printf ("the queue is empty! Cannot continue to delete! \ n");
    Printf ("after deletion, the queue length is:% d \ n", lengthqueue & Q));
    DstoryQueue(&Q);
    Printf ("destroyed!");

    return 0;
}
Status InitQueue(Queue* Q)
{
    Q->base = (Queue*)malloc(sizeof(ElemType) * MaxSize);
    if (!Q->base)
        exit(0);
    Q->front = Q->rear = 0;

    return TRUE;
}
Status InsertQueue(Queue *Q, ElemType e)
{
    if ((Q->rear + 1) % MaxSize == Q->front)
        return ERROR;
    Q->base[Q->rear] = e;
    Q->rear = (Q->rear + 1) % MaxSize;

    return TRUE;
}
Status DeleteQueue(Queue* Q, ElemType* e)
{
    if (Q->front == Q->rear)
        return ERROR;
    *e = Q->base[Q->front];
    Q->front = (Q->front + 1) % MaxSize;

    return TRUE;
}
Status LengthQueue(Queue* Q)
{
    return ((Q->rear-Q->front+MaxSize)%MaxSize);
}
void DstoryQueue(Queue* Q)
{
    free(Q->base);
    Q->base = NULL;
    Q->front = Q->rear = 0;
}