summaryrefslogtreecommitdiff
path: root/c/dataStructure/栈和队列/队列/循环队列/queue.c
blob: 2c7f7817959a37fbbf328311d0543264366044f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "queue.h"

bool InitQueue(Queue * q)
{
    q->base = (int *) malloc (sizeof(int) * MAXSIZE);
    if (!q->base)
    {
        fprintf(stderr,"Failed to allocate memory!\n");
        return false;
    }

    q->front = q->rear = 0;
}

bool EnQueue(Queue * q, int e)
{
    if ((q->rear + 1)%MAXSIZE == q->front)
    {
        fprintf(stderr,"Queue is full!\n");
        return false;
    }

    q->base[q->rear] = e;
    q->rear = (q->rear + 1) % MAXSIZE;

    return true;
}

bool DeQueue(Queue * q, int * e)
{
    if (q->front == q->rear)
    {
        fprintf(stderr,"Queue is empty");
        return false;
    }

    *e = q->base[q->front];
    q->front = (q->front + 1) % MAXSIZE;

    return true;
}

int LengthQueue(Queue * q)
{
    return (q->rear - q->front + MAXSIZE) % MAXSIZE;
}

int GetHead(Queue * q)
{
    if (q->front != q->rear)
        return q->base[q->front];
    return -1;
}