Data Structure - Queue

1. Definition of queue

Queue, the English name is queue, is a very common data structure.
In our life, we can see queues everywhere. In the cafeteria, a queue is a queue; an ATM queue to withdraw money is also a queue. They all have a feature that the first to come is served first.
FIFO, First In First Out, simply and clearly describes the characteristics of the queue, first in first out. According to the characteristics of this queuing, we can also draw that the queue is only allowed to be inserted from one end (the tail of the queue) and come out from one end (the head of the queue).

2, the realization of the queue

A queue is actually a special kind of linear table. Like a linear list, it also has two implementations: an array and a linked list.

Let's first look at how arrays implement queues.

 

#include<stdio.h>  
#include<malloc.h>

typedef int QElemType;

#define OK 1;
#define ERROR 0;

typedef struct Queue
{
    QElemType data[6];
    int front;
    int rear;
} sqqueue;

int main(void)
{
    SqQueue queue;
    initQueue(&queue);
    enQueue(&queue, 1);
    enQueue(&queue, 2);
    enQueue(&queue, 3);
    enQueue(&queue, 4);
    readQueue( & queue);
    outQueue(&queue);
    readQueue( & queue);
}

int initQueue(SqQueue *Q)
{
    Q->front = 0;
    Q->rear  = 0;

    return OK;
}

int enQueue(SqQueue *Q, int value)
{
    if(isFull(Q)){
        printf( "The queue is full, no more elements can be inserted!\n " );
         return ERROR;
    }
    Q->data[Q->rear] = value;
    Q->rear = (Q->rear+1) % 6;

    return OK;
}

QElemType outQueue(SqQueue *Q)
{
    QElemType value;
    if (isEmpty(Q)) {
        printf( "The queue is empty, dequeue failed!\n " );
         return ERROR;
    }
    value = Q->data[Q->front];
    Q->front = (Q->front+1) % 6;
    return value;
}


int readQueue(SqQueue *Q)
{
    int i = Q->front;

    printf( " traverse the queue: \n " );
     while (i != Q-> rear)
    {
        printf("%d  ", Q->data[i]);
        i = (i+1) % 6; 
    }
    printf("\n");
    return 0;
}

int isFull(SqQueue *Q)
{
    if((Q->rear+1) % 6 == Q->front){
          return OK;
    }else{
        return ERROR;
    }

}

int isEmpty(SqQueue *Q)
{
    if(Q->front == Q->rear){
         return OK;
    } else {
        return ERROR;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324738695&siteId=291194637